veko
ORO Homoiconic Language • Custom VM • Wasm 3.0 (vvm) • Native x86_64 & arm64

The Veko Cookbook & Rosetta Stone

Practical, copy-ready recipes and side-by-side translations for developers arriving from Go, Rust, Zig, Python, and TypeScript — spanning CLI workspaces, /or error recovery, .secret hygiene, Zero-FFI SQLite ORM, HTTP/1.1 + HTTP/2 + QUIC HTTP/3 services, shared-nothing concurrency, homoiconic [ ... ] mini-DSLs, native desktop UIs, and WebAssembly 3.0 sandboxes.

The Veko Cookbook — Practical Recipes & Rosetta Stone


Chapter 1: The Veko Rosetta Stone & Language Ergonomics

SYNTAX & HOMOICONICITY

Whitespace Disambiguation & Two-Pass Pratt Homoiconic Engine

How [tight] vs [spaced] tokens let kebab-case prefix calls coexist cleanly with infix math, UFCS chains, and macros.

Interactive SVG • Click any node (6 components)
LEXICAL DISAMBIGUATION lexer.vk TWO-PASS PRATT ENGINE parser.vk HOMOICONIC EVALUATION macro_eval.vk + lib/dialect.vk Token stream Typed literals Arity table AST + RawBlock Block values Lexer 4 Whitespace Rules [tight] vs [spaced] bits Lexer First-Class Literals 5s, 64kb, 0xFF, '...' Parser Pass 1 Pass 1: Signature Scan fn / struct / def / use Parser Pass 2 Pass 2: Pratt Precedence BP 80 postfix .. BP 10 pipe Homoiconicity quote & compose Code-as-Data Templates Dialects parse-block Dialects Embedded Domain Grammars
Components:
Lexer
4 Whitespace Rules
lexer.vk
Component 1 of 6
Architectural Role & Purpose

Eliminates grammar ambiguity using single-character attachment flags.

Contextual Description & System Interaction

Inspect exact attachment flags anytime with veko inspect --tokens.

Core Functionality & Mechanics
  • n - 1 (subtraction) vs n-1 (kebab word) vs -1 (negative literal)
  • a / b (division) vs str/join (module path) vs /or (refinement)
  • buf[0..n] & s.trim (tight postfix) vs .tls (spaced enum)
Lexer
First-Class Literals
lexer.vk
Component 2 of 6
Architectural Role & Purpose

Parses human-readable durations, binary sizes, hex/binary ints, and UTF-8 strings.

Contextual Description & System Interaction

Eliminates magic numbers in network timeouts and buffer capacities.

Core Functionality & Mechanics
  • Durations scale to i64 nanoseconds (500ms, 3s, 2m)
  • Binary sizes scale by powers of 1024 (64b, 4kb, 16mb)
  • Single-quoted UTF-8 strings avoid JSON double-quote escaping
Parser Pass 1
Pass 1: Signature Scan
parser.vk
Component 3 of 6
Architectural Role & Purpose

Collects top-level function arities, refinements, structs, and module imports.

Contextual Description & System Interaction

Makes parentheseless prefix calls deterministic without forward declarations.

Core Functionality & Mechanics
  • Enables order-independent top-level mutually recursive functions
  • Computes exact call arity (+1 for /or or value refinements)
  • Registers macro definitions before Pass 2 expression parsing
Parser Pass 2
Pass 2: Pratt Precedence
parser.vk
Component 4 of 6
Architectural Role & Purpose

Binds tight postfix chains, prefix word arguments, infix math, comparisons, and \ pipes.

Contextual Description & System Interaction

Ensures expressions like a + b == c and raw \ json/decode read naturally.

Core Functionality & Mechanics
  • BP 80: tight .field, .ufcs, and [idx] / [lo..hi] slicing
  • BP 60..30: * / % >>> & then + - | ^ then == != < <= > >=
  • BP 10: left-to-right \ pipe feeds result as arg 1 of next word
Homoiconicity
quote & compose
macro_eval.vk
Component 5 of 6
Architectural Role & Purpose

Treats [ ... ] blocks as inspectable values and splices computed expressions cleanly.

Contextual Description & System Interaction

Delivers Lisp-grade metaprogramming without parentheses or backtick clutter.

Core Functionality & Mechanics
  • quote [ ... ] returns unevaluated token/value blocks
  • compose evaluates only parenthesized (expr) slots
  • macro transforms raw argument blocks at compile time
Dialects
parse-block Dialects
parser.vk lib/dialect.vk
Component 6 of 6
Architectural Role & Purpose

Matches typed pattern rules over homoiconic blocks to drive custom DSLs.

Contextual Description & System Interaction

Lets teams craft readable domain dialects without writing external parsers.

Core Functionality & Mechanics
  • Matches literals, typed captures, enums, and nested sub-blocks
  • Powers firewall rules, SQL-like queries, and vault ACL policies
  • Runs identically on VM, Wasm 3.0, and Native binaries

Recipe 1.1: Translating Go, Rust, Python & TypeScript Habits into Idiomatic Veko

Newcomers write fluent Veko fastest when they see familiar constructs side-by-side with their idiomatic Veko counterparts:

Task Go / Rust / Python / TS Habit Idiomatic Veko (.vk)
Call a 2-arg function os.WriteFile(path, data) os/write-file path data
Nested call in math / loop while i < len(items) while i < (len items) [ ... ]
Call a 0-arg function hostBinPath() host-bin-path
Subtraction & division n-1, total/count n - 1, total / count (spaces required!)
Negative literal argument seek(fd, -1) seek fd -1 (tight -1, spaced after fd)
Strings & interpolation f"https://{host}:{port}" https://{host}:{port} or 'literal\n'
1-arg method chains raw.trim().toLowerCase() raw.trim.lower
Multi-step data pipeline items.filter(...).map(...) items \ filter fn [x] [...] \ map fn [x] [...]
In-place buffer mutation buf.push(10) / push(&mut buf, 10) bytes/push mut buf 10 (mut on both sides)
Fallback on error / missing key if err != nil / try...catch port = str/to-i64/or raw [ 443 ]
Propagate contextual error return fmt.Errorf("...: %w", err) raw = os/read-file/or p [e -> return (err read {p}: {mold e})]
Unit return / JSON null None / null / () / nil .ok (unit action) and .null (wire JSON null)

Recipe 1.2: Side-by-Side Service Function — Go & Rust vs. Veko

Consider loading a JSON peer list over HTTPS with a 3-second timeout, falling back to a local cache file, filtering active endpoints, and returning trimmed URLs.

In Go (imperative error sprawl):

GO
func activePeers(endpoint string) ([]string, error) {
    client := &http.Client{Timeout: 3 * time.Second}
    resp, err := client.Get(endpoint)
    var raw []byte
    if err != nil {
        raw, err = os.ReadFile("peers.cache.json")
        if err != nil {
            return nil, err
        }
    } else {
        defer resp.Body.Close()
        raw, err = io.ReadAll(resp.Body)
        if err != nil {
            return nil, err
        }
    }
    var peers []Peer
    if err := json.Unmarshal(raw, &peers); err != nil {
        return nil, err
    }
    var urls []string
    for _, p := range peers {
        if p.Active {
            urls = append(urls, strings.TrimSpace(p.URL))
        }
    }
    return urls, nil
}

In Idiomatic Veko (peers.vk):

VEKO
use [nc = net/client, j = json]

pub active-peers = fn [endpoint str] block[str] [
    raw = (nc/get/or endpoint (nc/RequestOpts { timeout = 3s }) [
        body_str = os/read-file/or 'peers.cache.json' [e ->
            return (err `peer lookup failed: {mold e}`)
        ]
        nc/HttpResponse { status = 200, reason = 'OK', headers = {}, body = (bytes/from-str body_str), final_url = endpoint }
    ]).body

    (bytes/to-str raw)
        \ j/decode
        \ filter fn [p] [ p.active ]
        \ map fn [p] [ p.url.trim ]
]

Notice how Veko eliminates both hidden exceptions and repetitive if err != nil blocks while keeping every failure boundary explicit on the page.

Recipe 1.3: Readability & Writability vs. Other Languages

Because Veko combines single-owner ORO systems memory (Native, WebAssembly 3.0, and 64-bit VM targets with zero GC pauses) and Rebol/Elixir-inspired expression ergonomics, its learning curve splits distinctly between Day 1 familiarity and Day 14 fluency:

Dimension Score Why
First-hour familiarity 5.5 / 10 Unlearning f(x), n-1, "strings", and null takes deliberate attention for the first few hours.
Steady-state readability 9.0 / 10 Near-zero syntactic noise; explicit mut at call sites; /or eliminates both hidden exceptions and 4-line error boilerplate; linear \ dataflow.
Steady-state writability 8.5 / 10 Very low ceremony, gradual types (prototype dynamically, lock down --strict-types for production), and homoiconic blocks/templates. Slight tax from fixed-arity memorization and explicit mut.
  • vs. Go (Readability: Veko >= Go | Writability: Veko > Go): Go and Veko both reject hidden magic. Veko pulls ahead on signal-to-noise ratio by replacing vertical if err != nil { return nil, err } repetition with inline /or [ ... ] and \ pipelines, while Go leads on Day-1 C-syntax familiarity and third-party IDE ecosystem size.
  • vs. Rust (Readability: Veko >> Rust | Writability: Veko >> Rust): Both enforce ownership, explicit mutation (&mut vs mut), and zero-GC safety. Veko delivers single-owner determinism, shared-nothing spawn/chan, and .secret taint safety without <'a, T: Send + Sync + 'static>, Arc<Mutex<...>>, or turbofish ::<> noise — trading away only complex multi-lifetime borrow graphs.
  • vs. Zig (Readability: Veko > Zig | Writability: Veko > Zig): Zig's catch |err| and orelse are close cousins to Veko's /or, and both prize defer and explicitness. Veko is faster to write and scan for networking, CLI, codec, web, and backend work (built-in strings/maps, backtick templates, pipes, gradual typing), while Zig stays lower-level for raw OS kernels or custom allocators.
  • vs. Elixir / Clojure / Rebol (Readability: Veko >= Elixir, > Clojure/Rebol | Writability: Tie): Captures Elixir's |> (\ in Veko) and Lisp's quote/compose homoiconicity without outer parenthesis walls — and solves classic Rebol's dynamic-arity scaling hazard via lexical scoping, explicit use/pub modules, mut borrow checking, and --strict-types.
  • vs. Python / TypeScript (Readability: Tie | Writability: Day-1 Python/TS > Veko; Maintenance Veko > Python/TS): Python and TypeScript feel effortless on Day 1 because everyone already knows their syntax, whereas over time hidden exceptions, None/undefined landmines, shared-reference mutation, and async/await coloring erode clarity. Veko reads like clean pseudocode while encoding mutation, errors, secrets, and capabilities directly on the page.

Chapter 2: Workspaces, CLI Subcommands, Config & Secrets

CAPABILITY GOVERNANCE

Defense-in-Depth Capability Gates, .secret Firewall & Supply-Chain Trust

Compile-time allow-caps enforcement, cryptographic taint tracking, zero-trust Wasm sandboxes, and signed VKP1 packages.

Interactive SVG • Click any node (5 components)
COMPILE-TIME POLICY & SUPPLY CHAIN veko.vk + types.vk + pkg/vkp.vk RUNTIME SANDBOXES & SINK FIREWALLS oro_vm.vk + vvm + native PAL Static audit .secret blocked Verified deps Cap mask Sink checks Manifest Policy veko.vk allow-caps .fs .clocks .env .net .exec .ui FFI Isolation Default-Deny .ffi Gate --allow-ffi / VEKO_ALLOW_FFI=1 Supply Chain Signed VKP1 Bundles Merkle SHA-256 + Ed25519/ML-DSA Taint Firewall Compile + Runtime .secret Zero Leakage Across Sinks Runtime Isolation VM & Wasm HostSandbox --allow-* + fuel + SSRF block
Components:
Manifest Policy
veko.vk allow-caps
types.vk main.vk
Component 1 of 5
Architectural Role & Purpose

Declares the exact OS capabilities permitted inside the workspace module graph.

Contextual Description & System Interaction

Prevents utility libraries from silently opening sockets or spawning processes.

Core Functionality & Mechanics
  • Transitively audits imported modules for unauthorized syscalls
  • Enforces canonical real-path confinement against ../ traversal
  • .exec and .ui are explicit opt-in capability bits
FFI Isolation
Default-Deny .ffi Gate
lib/ffi.vk types.vk
Component 2 of 5
Architectural Role & Purpose

Keeps foreign C-ABI shared libraries disabled by default and banned in Wasm.

Contextual Description & System Interaction

Ensures pure-Veko builds remain memory-safe and self-contained by default.

Core Functionality & Mechanics
  • Requires explicit CLI/manifest opt-in to load .dll/.so/.dylib
  • Uses static AOT trampolines (zero JIT RWX pages)
  • Preserves 100% static Linux ELF64 when .ffi is unused
Supply Chain
Signed VKP1 Bundles
lib/pkg/vkp.vk
Component 3 of 5
Architectural Role & Purpose

Verifies cryptographic package signatures against pinned trust-keys before compilation.

Contextual Description & System Interaction

Eliminates unsigned dependency injection across teams and CI pipelines.

Core Functionality & Mechanics
  • Computes deterministic Merkle root over sorted .vk module entries
  • Supports classical Ed25519 and post-quantum ML-DSA-65 signers
  • veko pkg verify rejects tampered bytes or untrusted keys
Taint Firewall
Compile + Runtime .secret
types.vk runtime.vk
Component 4 of 5
Architectural Role & Purpose

Blocks secret-tagged values from leaving process memory in cleartext.

Contextual Description & System Interaction

Makes accidental API key or private key exfiltration a compile/runtime error.

Core Functionality & Mechanics
  • Statically & dynamically blocks net/*, http/*, os/write-file, json/encode
  • Blocks chan/send, spawn captures, ui/present, and ffi/* calls
  • Explicit unsealing only via crypto/seal/with-open scoped callback
Runtime Isolation
VM & Wasm HostSandbox
oro_vm.vk runtime_pal*.vk
Component 5 of 5
Architectural Role & Purpose

Enforces defense-in-depth host policies at runtime for scripts and plugins.

Contextual Description & System Interaction

Lets operators run third-party Veko workloads safely on shared infrastructure.

Core Functionality & Mechanics
  • Blocks loopback/RFC1918/link-local SSRF unless --allow-private-net
  • Caps Wasm CPU fuel (--fuel) and linear RAM pages (--mem-pages)
  • Confines file reads/writes to --allow-fs=<dir> chroot

Recipe 2.1: Zero-Flag Workspaces & Automatic Capability Tightening (veko init & veko mod sync)

Scaffold a workspace with a veko.vk manifest and let the compiler audit and lock down the exact minimal OS capability bitmask ([.fs .clocks .env .net]):

POWERSHELL
# Scaffold a web, CLI, GUI, or library workspace
veko init sync-agent --cli
cd sync-agent

# Run, type-check, test, and compile directly from veko.vk
veko .
veko check --strict-types src/main.vk
veko test
veko compile --native src/main.vk -o dist/sync-agent.exe

# Scan all transitive imports and tighten allow-caps in veko.vk to the exact minimum
veko mod sync

For quick one-off scripts outside a workspace, grant capabilities explicitly on the CLI:

POWERSHELL
veko -C fs,net tools/ping_health.vk
veko run -e 'println `SHA-256 ready: {1 << 8}`'

Recipe 2.2: Declarative Subcommand & Flag CLI (lib/cli.vk)

Build structured multi-subcommand CLIs with typed flags, defaults, and automatic --help rendering:

VEKO
use [cli]

build-cli = fn [] cli/App [
    mut app = cli/new-app 'deploy-ctl' '1.0.0' 'Pure-Veko release rollout utility'
    mut ship = cli/new-cmd 'ship' 'Roll out a signed release bundle'
    cli/add-flag mut ship (cli/FlagSpec { name = 'env',     short = 'e', kind = .string,  default_val = 'staging', help = 'Target environment' })
    cli/add-flag mut ship (cli/FlagSpec { name = 'workers', short = 'w', kind = .int,     default_val = 4,         help = 'Parallel rollout workers' })
    cli/add-flag mut ship (cli/FlagSpec { name = 'dry-run', short = 'n', kind = .boolean, default_val = false,     help = 'Validate without mutating' })
    cli/add-cmd mut app ship
    app
]

main = fn [] any [
    app = build-cli
    parsed = cli/parse/or app os/args [e ->
        println (cli/help-text app)
        return e
    ]
    if parsed.cmd == 'ship' [
        env_name = cli/get-str parsed 'env' 'staging'
        n_work   = cli/get-int parsed 'workers' 4
        dry      = cli/get-bool parsed 'dry-run' false
        println `Rolling out to {env_name} with {n_work} workers (dry_run={dry})`
    ]
    .ok
]

Recipe 2.3: Layered TOML + Environment Configuration with .secret Hygiene

Load human-friendly codec/toml configuration files while keeping API tokens and signing keys quarantined inside Veko's .secret type firewall (zeroized deterministically when scope exits):

VEKO
use [toml = codec/toml]

pub ServiceConfig = struct {
    host       str        = '127.0.0.1'
    port       i64        = 8080
    api_secret secret str = ''
}

pub load-config = fn [path str] ServiceConfig [
    raw = os/read-file/or path [ '' ]
    doc = if raw != '' [ toml/decode/or raw [ {} ] ] else [ {} ]

    host = str/append '' (map/get/or doc 'host' [ os/getenv/or 'APP_HOST' [ '127.0.0.1' ] ])
    port = as-i64 (map/get/or doc 'port' [ str/to-i64/or (os/getenv/or 'APP_PORT' [ '8080' ]) [ 8080 ] ])

    // Secret environment variable is tainted as `secret` and wiped on scope exit
    tok = os/getenv/secret/or 'APP_API_SECRET' [ secret '' ]
    println `Loaded config on {host}:{port} (token={tok})`  // prints token=<secret>

    ServiceConfig {
        host       = host
        port       = port
        api_secret = tok
    }
]

Chapter 3: Zero-nil Error Recovery, Refinements & ORO Memory

MEMORY MODEL

ORO Single-Owner Memory: Borrow, Move, mut Loan & Copy-on-Write

Rust-grade deterministic cleanup and zero garbage collector pauses without lifetime annotations.

Interactive SVG • Click any node (6 components)
ZERO-COPY FAST PATH (RC == 1) 99% of calls & mutations SHARED SPLIT & SCOPE EXIT Cycle-free DAG + zeroize 16B header rc == 1 bind / return mut when rc > 1 scope exit old rc-- Allocation 1. Create Value SSO <=14B or Unique Slab Fast Call 2. Read-Only Call Zero-Cost Borrow In-Place Mutation 3. Explicit mut Loan mut param + mut call site Move / Share 4. Binding & Return Ownership Transfer Copy-on-Write 5. Lazy CoW Split ensure_unique on rc > 1 Cleanup 6. Deterministic Drop Free-List + .secret Wipe
Components:
Allocation
1. Create Value
runtime.vk native_rt.vk
Component 1 of 6
Architectural Role & Purpose

Allocates scalars and <=14B strings/bytes inline in 16B Value; larger data gets rc=1 slab.

Contextual Description & System Interaction

Eliminates small-string heap churn right at creation.

Core Functionality & Mechanics
  • Zero heap allocation for numbers, bools, enums, and short strings
  • 12-bucket power-of-two slab free-list gives O(1) allocation
  • Every new heap container starts uniquely owned (rc == 1)
Fast Call
2. Read-Only Call
vko_emit.vk native_emit.vk
Component 2 of 6
Architectural Role & Purpose

Normal function parameters borrow the 16-byte Value header with zero refcount traffic.

Contextual Description & System Interaction

Makes passing large buffers and maps to helper functions free.

Core Functionality & Mechanics
  • Caller retains ownership; callee reads without retain/release
  • Zero atomic instructions on shared-nothing thread-local heaps
  • Works identically for str, bytes, block, map, and structs
In-Place Mutation
3. Explicit mut Loan
types.vk native_emit.vk
Component 3 of 6
Architectural Role & Purpose

Mutates uniquely owned buffers, blocks, maps, and struct fields directly in place.

Contextual Description & System Interaction

Makes every side effect visible at the call site while keeping rc == 1.

Core Functionality & Mechanics
  • Requires mut at both declaration and call site (push mut xs v)
  • Direct struct field loans (mut cv.pixels) avoid temporary clones
  • O(1) amortized append and in-place byte/pixel updates
Move / Share
4. Binding & Return
oro_vm.vk native_rt.vk
Component 4 of 6
Architectural Role & Purpose

Rebinding or returning transfers ownership cleanly; aliasing increments non-atomic rc.

Contextual Description & System Interaction

Because values form a strict DAG, a tracing cycle collector is never needed.

Core Functionality & Mechanics
  • Returning local buffers transfers the slab without copying
  • Closure captures freeze outer values into acyclic snapshots
  • Structural acyclicity guarantees zero reference cycles
Copy-on-Write
5. Lazy CoW Split
runtime.vk native_rt.vk
Component 5 of 6
Architectural Role & Purpose

Clones the backing slab only at the exact moment a shared container is mutated.

Contextual Description & System Interaction

Gives functional value safety with imperative C-speed mutation.

Core Functionality & Mechanics
  • If rc == 1: mutates in place with zero copy
  • If rc > 1: allocates fresh slab, copies payload, decrements old rc
  • Preserves value semantics so aliases never observe spooky action
Cleanup
6. Deterministic Drop
runtime.vk native_rt.vk
Component 6 of 6
Architectural Role & Purpose

Reclaims dead slabs immediately at lexical scope exit or /or unwind.

Contextual Description & System Interaction

Predictable microsecond latency with zero stop-the-world GC pauses.

Core Functionality & Mechanics
  • Returns slab to O(1) size-class bucket when rc hits 0
  • Scrubs flag_secret slabs with volatile zero bytes before reuse
  • Runs LIFO defer blocks on return and error recovery

Recipe 3.1: User-Declarable Slash Refinements & Contextual /or [e -> ...]

Any function can declare optional /refinement modifiers with defaults, and callers can combine refinements in left-to-right order plus attach /or error recovery:

VEKO
dial-upstream = fn [host str /port p i64 = 443 /tls secure bool = true] str [
    if host.trim == '' [ return (err 'upstream host cannot be empty') ]
    scheme = if secure [ 'https' ] else [ 'http' ]
    `{scheme}://{host.trim}:{p}`
]

// Base arity uses defaults (p = 443, secure = true)
prod_url = dial-upstream 'veko-lang.org'

// Extend arity cleanly at the call site via /port/tls
dev_url = dial-upstream/port/tls '127.0.0.1' 8080 false

// Recover inline and inspect the caught error `e`
safe_url = dial-upstream/or '' [e ->
    println `Falling back to loopback ({mold e})`
    'http://127.0.0.1:8080'
]

Recipe 3.2: Deterministic LIFO defer Cleanup on Return and /or Unwind

Pair every file handle, socket, or temporary directory with defer [ ... ] on the line immediately below acquisition so cleanup runs in LIFO order on both normal return and early error returns:

VEKO
use [fs]

write-verified-report = fn [dst_path str, lines block[str]] any [
    tmp_dir = str/join [(os/temp-dir) '/report_stage_' (mold (time/unix))] ''
    _ = fs/mkdir-all tmp_dir
    defer [ _ = fs/remove-all tmp_dir ]

    stage_file = `{tmp_dir}/draft.txt`
    payload = bytes/from-str (str/join lines '\n')
    _ = fs/write-atomic/or stage_file payload [e ->
        return (err `staging write failed: {mold e}`)
    ]
    fs/copy-file stage_file dst_path
]

Recipe 3.3: In-Place Byte Slab Building & Disjoint Field Loans (mut)

Pre-allocate binary packet buffers once with bytes/with-cap and pass explicit mut loans (including disjoint struct field loans like mut state.tx_buf) for zero-copy framing:

VEKO
PacketState = struct {
    stream_id i64
    tx_buf    bytes
}

append-tlv-frame = fn [mut buf bytes, tag i64, body bytes] [
    _ = bytes/push mut buf (tag & 0xff)
    _ = bytes/push-u16-be mut buf (len body)
    _ = bytes/push-all mut buf body
    .ok
]

build-hello-packet = fn [] bytes [
    mut st = PacketState {
        stream_id = 1
        tx_buf    = (bytes/with-cap 128)
    }
    append-tlv-frame mut st.tx_buf 0x01 (bytes/from-str 'VEKO-1.0')
    append-tlv-frame mut st.tx_buf 0x02 (bytes/from-str 'veko-lang.org')
    st.tx_buf
]

Chapter 4: Files, Streams, Archives, Compression & Regex

79-MODULE STDLIB & PQC

Pure-Veko Standard Library & Post-Quantum Cryptography Architecture

1,043 exported structs and functions across 79 modules — from core data structures to NIST FIPS 203/204/205 PQC.

Interactive SVG • Click any node (6 components)
CORE DATA, CLI, CODECS & ARCHIVES Zero OS capabilities required CLASSICAL & POST-QUANTUM CRYPTOGRAPHY lib/crypto/* + lib/auth/* buf / bits Wire frames SHA3 / SHAKE AES-GCM / EdDSA ML-KEM / ML-DSA TLS / Vault / JWT Foundations Core, Text, Math & CLI fmt, cli, coll, seq, regex, utf8 Serialization Codecs, Wire & Archives cbor, csv, toml, der, deflate, zip Systems Layer Streams, Reactor, DB & UI io, reactor, web, db/*, durable, ui Classical Crypto AEAD, Hashes & Curves AES-GCM, ChaCha20, SHA-2/3, X25519 Post-Quantum NIST FIPS 203 / 204 / 205 ML-KEM, ML-DSA & SLH-DSA Envelope & Auth crypto/seal & Auth Tokens Sealed Envelopes + JWT/OAuth2/TOTP
Components:
Foundations
Core, Text, Math & CLI
lib/fmt.vk lib/cli.vk lib/coll.vk
Component 1 of 6
Architectural Role & Purpose

Provides formatting, subcommand CLI parsing, sets/rings/heaps/LRU, regex NFA, and UTF-8.

Contextual Description & System Interaction

Everything needed to build polished CLI tools and data pipelines.

Core Functionality & Mechanics
  • cli/parse handles flags, subcommands, and --help generation
  • coll provides Set, Ring, Heap, Lru, and Memo containers
  • testing, diff, semver, retry, template, slog, and datetime
Serialization
Codecs, Wire & Archives
lib/codec/* lib/archive/*
Component 2 of 6
Architectural Role & Purpose

Encodes and decodes binary and text wire formats plus compressed TAR/ZIP archives.

Contextual Description & System Interaction

Zero-FFI parsers protect against C buffer overflows on untrusted inputs.

Core Functionality & Mechanics
  • JSON (builtin), CBOR, CSV, INI, TOML, URL, Hex/Base64, VBIN
  • codec/wire declarative binary struct schemas + ASN.1 DER/PEM
  • compress/deflate (DEFLATE/zlib/gzip) + archive/tar & archive/zip
Systems Layer
Streams, Reactor, DB & UI
lib/reactor.vk lib/web.vk lib/durable.vk
Component 3 of 6
Architectural Role & Purpose

Builds high-level networking, persistence, workflows, and UIs over the capability PAL.

Contextual Description & System Interaction

Connects pure functional codecs to real-world servers, databases, and desktops.

Core Functionality & Mechanics
  • io/Stream polymorphism over files, sockets, TLS, and memory buffers
  • reactor + web + net/client + db/{kv,postgres,redis} + durable/*
  • tui TrueColor diffing terminal + ui/canvas RGBA32 & ui/widgets
Classical Crypto
AEAD, Hashes & Curves
lib/crypto/aes.vk lib/crypto/x25519.vk
Component 4 of 6
Architectural Role & Purpose

Constant-time symmetric AEADs, cryptographic Sponge/Merkle hashes, KDFs, and elliptic curves.

Contextual Description & System Interaction

Provides audited pure-Veko implementations of modern internet cryptography.

Core Functionality & Mechanics
  • AES-256-GCM (hardware AES-NI accelerated) & XChaCha20-Poly1305
  • SHA-256/384/512, HKDF, SHA3-256/512, SHAKE128/256, BLAKE2b
  • Argon2id & PBKDF2 + X25519, Ed25519, P-256 ECDSA & RSA-PSS
Post-Quantum
NIST FIPS 203 / 204 / 205
lib/crypto/mlkem.vk lib/crypto/mldsa.vk
Component 5 of 6
Architectural Role & Purpose

Quantum-resistant lattice KEMs, lattice signatures, and stateless hash signatures.

Contextual Description & System Interaction

Future-proofs TLS 1.3 key exchange, JWT tokens, vaults, and VKP1 package signing.

Core Functionality & Mechanics
  • ML-KEM-512/768/1024 (FIPS 203) key encapsulation
  • ML-DSA-44/65/87 (FIPS 204) lattice digital signatures
  • SLH-DSA SHA2/SHAKE (FIPS 205) stateless hash signatures
Envelope & Auth
crypto/seal & Auth Tokens
lib/crypto/seal.vk lib/auth/jwt.vk
Component 6 of 6
Architectural Role & Purpose

Combines sealed AEAD envelopes with EdDSA/ML-DSA65 JWTs, OAuth2 PKCE, and RFC 6238 TOTP.

Contextual Description & System Interaction

Bridges low-level cryptographic primitives directly to safe application APIs.

Core Functionality & Mechanics
  • pub sealed Sealed prevents raw ciphertext field tampering
  • seal/with-open decrypts into scoped bytes and zeroizes on return
  • auth/jwt signs HS256, EdDSA, and post-quantum ML-DSA-65 tokens

Recipe 4.1: Polymorphic io/Stream Pipelines (Memory, Files & TLS Sockets)

Write protocol parsers and serializers against io/Stream so unit tests feed io/mem-stream in memory with zero capabilities while production code passes TCP or TLS 1.3 streams:

VEKO
use [io]

write-netstring = fn [mut s io/Stream, msg str] i64 [
    raw = bytes/from-str msg
    frame = bytes/from-str `{(len raw)}:{msg},`
    io/write-all mut s frame
]

// Test purely in memory with zero .fs or .net capabilities
mut mem = io/mem-stream (bytes/with-cap 0)
_ = write-netstring mut mem 'homoiconic'
wire_text = bytes/to-str (io/read-all mut mem)  // '10:homoiconic,'

Recipe 4.2: Linear-Time ReDoS-Proof Regex Capture Groups (lib/text/re.vk)

Veko's text/re compiles patterns to a Thompson NFA with guaranteed O(n * m) execution time — immune to catastrophic backtracking on untrusted user input:

VEKO
use [re = text/re]

sem_rx = re/compile '([a-z0-9_]+)@([0-9]+\\.[0-9]+\\.[0-9]+)'
m = re/match sem_rx 'http_router@1.2.0'
if m.matched [
    pkg_name = m.groups[1]   // 'http_router'
    pkg_ver  = m.groups[2]   // '1.2.0'
    println `Resolved package {pkg_name} version {pkg_ver}`
]

Recipe 4.3: Zstandard Compression & Deterministic TAR/ZIP Archives

Compress payloads with RFC 8878 Zstandard (compress/zstd) and bundle multi-file release archives in memory with archive/zip or archive/tar:

VEKO
use [zstd = compress/zstd, zip = archive/zip]

pack-diagnostic-bundle = fn [readme_txt str, log_json str] bytes [
    compressed_log = zstd/compress (bytes/from-str log_json)
    zip/pack [
        zip/ZipEntry { path = 'README.txt',    data = (bytes/from-str readme_txt), compress = true }
        zip/ZipEntry { path = 'events.json.zst', data = compressed_log,            compress = false }
    ]
]

Chapter 5: HTTP/1.1, HTTP/2, QUIC HTTP/3 & Homoiconic Web Apps

NETWORKING, WEB & DATABASES

Unified io/Stream Stack, Hybrid PQC TLS 1.3, Web Router & Zero-FFI Databases

End-to-end network services, HTML5 rendering, and wire-native database drivers running across all three runtimes.

Interactive SVG • Click any node (6 components)
TRANSPORT & SECURITY LAYER io/* + net/dns + net/tls13 HTTP, WEB & REAL-TIME LAYER web + html + net/websocket + http2 PERSISTENCE & PACKAGING db/kv + db/postgres + db/redis + vkp Encrypted stream HTTP/1.1 HTTPS / WSS State & sessions SQL & cache Polymorphic I/O io/Stream Capability Record io/fs + io/net + io/open Secure Transport DNS & Hybrid PQC TLS 1.3 RFC 8446 + X25519MLKEM768 Web Tier web Router & HTML5 DSL Middleware + auto-escaped html Protocols HTTP Client, HTTP/2 & WS net/client + http2 + websocket Embedded Store Embedded db/kv Engine CRC-32 WAL + put-sealed External DBs Postgres v3, Redis & Sidecar SCRAM-SHA-256 + RESP2/3
Components:
Polymorphic I/O
io/Stream Capability Record
lib/io.vk lib/io/net.vk
Component 1 of 6
Architectural Role & Purpose

Record-of-closures interface unifying TCP sockets, files, and in-memory test buffers.

Contextual Description & System Interaction

Decouples HTTP, TLS, and database codecs from raw socket handles.

Core Functionality & Mechanics
  • read, write, flush, and close closures without OOP classes
  • io/net wraps blocking or non-blocking TCP sockets cleanly
  • Enables 100% deterministic unit testing of protocol codecs
Secure Transport
DNS & Hybrid PQC TLS 1.3
lib/net/dns.vk lib/net/tls13.vk
Component 2 of 6
Architectural Role & Purpose

Resolves DNS records over UDP/TCP and negotiates TLS 1.3 with X.509 chain verification.

Contextual Description & System Interaction

Delivers modern encrypted transport in pure Veko with zero OpenSSL dependency.

Core Functionality & Mechanics
  • Hybrid X25519 + ML-KEM-768 post-quantum key share
  • AES-128/256-GCM & ChaCha20-Poly1305 record protection
  • Verifies RSA-PSS, ECDSA P-256, and Ed25519 X.509 certificates
Web Tier
web Router & HTML5 DSL
lib/web.vk lib/html.vk
Component 3 of 6
Architectural Role & Purpose

Routes parameterized paths (:id, *splat) through composable middleware and typed HTML5 nodes.

Contextual Description & System Interaction

Powers full-stack light/dark web applications and JSON APIs from one binary.

Core Functionality & Mechanics
  • serve-stream, serve-loop, and non-blocking serve-reactor
  • Built-in request-id, CORS, security-headers, and bearer auth
  • html/render auto-escapes text and blocks javascript: XSS URLs
Protocols
HTTP Client, HTTP/2 & WS
lib/net/client.vk lib/net/websocket.vk
Component 4 of 6
Architectural Role & Purpose

Provides redirect-following HTTP/1.1 batching, HTTP/2 HPACK framing, and RFC 6455 WebSockets.

Contextual Description & System Interaction

Supports both outbound microservice fan-out and bidirectional browser streams.

Core Functionality & Mechanics
  • net/client/request-batch multiplexes concurrent HTTP calls
  • codec/http2 & net/http2 implement HPACK and stream frames
  • net/websocket handles upgrade handshakes, masking, and ping/pong
Embedded Store
Embedded db/kv Engine
lib/db/kv.vk
Component 5 of 6
Architectural Role & Purpose

Crash-safe append-only log-structured key-value database with positioned pread/pwrite.

Contextual Description & System Interaction

Gives every Veko binary embedded ACID-like local persistence with zero C SQLite DLLs.

Core Functionality & Mechanics
  • CRC-32 frame checksums automatically truncate torn tail writes
  • Prefix scans, atomic batches, log compaction, and AES-GCM put-sealed
  • Foundation for lib/durable/object.vk and lib/durable/workflow.vk
External DBs
Postgres v3, Redis & Sidecar
lib/db/postgres.vk lib/db/redis.vk
Component 6 of 6
Architectural Role & Purpose

Speaks PostgreSQL v3 extended query wire protocol and Redis RESP directly over io/Stream.

Contextual Description & System Interaction

Connects natively to production Postgres and Redis clusters from VM, Wasm, or Native.

Core Functionality & Mechanics
  • PostgreSQL SCRAM-SHA-256 auth, parameterized $1 queries, transactions
  • Redis RESP2/3 pipelined GET/SET/HSET/LPUSH/PUBLISH commands
  • db/sidecar isolates external CLI engines over .exec stdio

Recipe 5.1: Concurrent Non-Blocking HTTP Batch Fetching, HEAD Probes & Keep-Alive Pools (lib/net/client.vk)

Fetch multiple endpoints concurrently on a single readiness reactor thread via nc/get-many (with built-in public CA root verification across Ed25519, ECDSA P-256/P-384, and RSA), issue zero-body nc/head checks, or reuse persistent sockets via nc/new-pool:

VEKO
use [nc = net/client]

probe-cluster = fn [urls block[str]] block[i64] [
    opts = nc/RequestOpts { timeout = 5s, pqc = true }
    responses = nc/get-many urls opts
    responses \ map fn [r] [
        if err? r [ 0 ] else [ r.status ]
    ]
]

check-release-size = fn [url str] str [
    r = nc/head url (nc/RequestOpts { timeout = 5s })
    map/get/or r.headers 'content-length' [ '0' ]
]

Recipe 5.2: XSS-Safe Homoiconic HTML5 Views & Web Router (lib/html.vk + lib/web.vk)

Author HTML5 components as native Veko [.tag { attrs } [ children ]] blocks where text nodes are automatically HTML-escaped against XSS, and GET routes automatically answer RFC-compliant HEAD requests:

VEKO
use [web, html]

status-card = fn [service_name str, proto str] block [
    [.article { class = 'card' } [
        [.h2 {} [`Service: {service_name}`]]
        [.p {} [`Active wire protocol: {proto}`]]
    ]]
]

pub make-app = fn [] web/App [
    mut app = web/new-app
    web/use-security-headers mut app

    web/get mut app '/status/:service' fn [req web/Request] web/Response [
        svc   = web/param req 'service' 'veko-site'
        proto = web/header req 'X-Veko-Proto' 'h1'
        web/view 200 (status-card svc proto)
    ]

    web/get mut app '/api/v1/ping' fn [req web/Request] web/Response [
        web/json-resp 200 { ok = true, proto = (web/header req 'X-Veko-Proto' 'h1') }
    ]
    app
]

Recipe 5.3: Multi-Worker Native TLS 1.3 + HTTP/2 (h2) + WAN QUIC HTTP/3 (h3)

Run one web/App across multi-core shared-nothing TCP :443 workers (https-accept-loop + https-worker-loop with mtime certificate hot-reload, 5s handshake deadlines, and HTTP/2 Rapid Reset guards), UDP :443 WAN QUIC v1 HTTP/3 (ReassemblyBuf + PTO retransmission), and TCP :80 (Let's Encrypt ACME HTTP-01 + 301 redirect) with zero reverse proxy:

VEKO
use [web, inet = io/net, tls = net/tls13]

serve-production = fn [cert_pem str, key_pem str, acme_dir str] any [
    _ = tls/ensure-dev-p256-identity cert_pem key_pem 'veko-lang.org'
    mut rel = tls/new-cert-reloader cert_pem key_pem

    // 1. Spawn port :80 ACME HTTP-01 + 301 HTTPS redirect reactor
    _ = spawn [
        r_ln = inet/listen-nonblock '0.0.0.0:80'
        _ = web/serve-reactor r_ln (web/make-acme-redirect-app acme_dir 'veko-lang.org' 443) (web/AsyncServerOpts { max_requests = 0 })
        .ok
    ]

    // 2. Spawn UDP :443 WAN QUIC v1 HTTP/3 listener
    usock = net/udp-bind '0.0.0.0' 443
    _ = spawn [
        mut h3_rel = tls/new-cert-reloader cert_pem key_pem
        _ = web/serve-h3 usock (fn [] any [ tls/get-identity mut h3_rel ]) (make-app) 0
        .ok
    ]

    // 3. Dispatch TCP :443 TLS 1.3 (h2 + http/1.1) across 4 shared-nothing workers
    work_ch = chan/new 128
    opts = web/HttpsServerOpts {
        max_requests      = 0
        handshake_timeout = 5s
        alt_svc           = 'h3=":443"; ma=86400'
    }
    mut w = 0
    while w < 4 [
        _ = spawn [
            _ = web/https-worker-loop work_ch (make-app) opts
            .ok
        ]
        w = w + 1
    ]
    ln = net/listen-tcp .ip '0.0.0.0:443'
    web/https-accept-loop ln mut rel work_ch 0
]

Recipe 5.4: Constant-Memory File, 206 Range & Chunked Response Streaming

Serve multi-hundred-megabyte SDK archives, video slices, or generated io/Stream feeds without buffering payloads in RAM (serve-static-range automatically switches to 64 KiB positioned os/pread streaming across HTTP/1.1 and flow-controlled HTTP/2 DATA frames for files and byte ranges > 256 KiB):

VEKO
use [io, web]

register-download-routes = fn [mut app web/App] [
    web/get mut app '/downloads/:archive' fn [req web/Request] web/Response [
        name  = web/param req 'archive' ''
        range = web/header req 'Range' ''
        web/serve-static-range 'downloads' name range
    ]

    web/get mut app '/events/export.ndjson' fn [req web/Request] web/Response [
        payload = bytes/from-str '{"seq":1,"ok":true}\n{"seq":2,"ok":true}\n'
        st = io/from-bytes payload
        // Pass -1 content_len (or use web/chunked-response) for HTTP/1.1 chunked / H2 DATA streaming
        web/stream-response 200 'application/x-ndjson' st (len payload)
    ]
]

Chapter 6: Zero-FFI SQLite 3, TLS PostgreSQL & RESP3 Redis

Recipe 6.1: Crash-Safe Schemas, B-Tree Indexes & Homoiconic JOIN Queries (lib/db/sqlite.vk)

Veko's db/sqlite reads and writes genuine 4096-byte "SQLite format 3\0" B-tree files—complete with a CRC-32-verified 'VKJRNL01' rollback journal, incremental dirty-page os/pwrite commits, multi-page 0x02/0x0a B-tree indexes, and relational INNER/LEFT JOIN—in 100% pure Veko with zero libsqlite3 dependencies:

VEKO
use [sq = db/sqlite]

Packages = sq/define-table 'packages' (quote [
    id        i64 .pk
    name      str .unique
    owner_id  i64 .index
    downloads i64 = 0
])

Authors = sq/define-table 'authors' (quote [
    id     i64 .pk
    handle str .unique
])

run-registry-store = fn [db_path str] block [
    mut db = sq/open db_path
    _ = sq/migrate mut db Authors
    _ = sq/migrate mut db Packages

    aid = sq/insert mut db Authors { handle = 'ada' }
    _ = sq/insert mut db Packages {
        name      = 'http_router'
        owner_id  = aid
        downloads = 42
    }
    _ = sq/save mut db

    // Homoiconic LEFT JOIN with qualified projections & indexed ordering
    sq/q db (quote [
        select [p.name a.handle p.downloads]
        from packages p
        left-join authors a on [p.owner_id == a.id]
        where [p.downloads >= 10]
        order-by [p.downloads .desc]
        limit 10
    ])
]

Recipe 6.2: Parameterized SQL Queries & Atomic Online Backups

Combine homoiconic sq/q queries with parameterized SQL (? placeholders) and zero-downtime atomic file snapshots via fs/write-atomic:

VEKO
use [fs, sq = db/sqlite]

increment-downloads = fn [db_path str, pkg_name str] enum [
    mut db = sq/open db_path
    _ = sq/exec mut db 'UPDATE packages SET downloads = downloads + 1 WHERE name = ?' [pkg_name]
    sq/save mut db
]

backup-sqlite-online = fn [db_path str, backup_path str] i64 [
    db = sq/open db_path
    snapshot = sq/to-bytes db
    fs/write-atomic backup_path snapshot
]

Recipe 6.3: Crash-Safe Append-Only KV & Secondary Indexes (lib/db/kv.vk + lib/db/query.vk)

For ultra-fast embedded state, pair db/kv with db/query secondary indexes:

VEKO
use [kv = db/kv, q = db/query]

mut store = kv/open-fast 'sessions.vkkv'
sessions  = q/define-table 'sessions' 'id' ['role']
_ = q/put-row mut store sessions { id = 'sess_01', user = 'ada', role = 'superadmin' }
admins = q/where-eq store sessions 'role' 'superadmin'
_ = kv/close mut store

Recipe 6.4: Pooled TLS PostgreSQL $1 Prepared Queries & RESP3 Redis Transactions (lib/db/postgres.vk + lib/db/redis.vk)

Scale stateless backend workers over bounded, health-checked PgPool (TLS 1.3 SSLRequest + SCRAM-SHA-256 + Extended Query $1, $2 binary parameters) and RedisPool (RESP3 HELLO 3 + MULTI/EXEC transactions):

VEKO
use [pg = db/postgres, rd = db/redis]

fetch-active-tenants = fn [pg_pool pg/PgPool, rd_pool rd/RedisPool, region str] any [
    rows = pg/with-conn pg_pool fn [mut conn pg/PgConn] any [
        pg/with-tx mut conn fn [mut tx pg/PgConn] any [
            pg/query-params mut tx
                'SELECT id, slug FROM tenants WHERE region = $1 AND active = $2'
                [region true]
        ]
    ]

    _ = rd/with-conn rd_pool fn [mut rconn rd/RedisConn] any [
        rd/with-tx mut rconn fn [mut q block] any [
            rd/tx-queue mut q ['INCR' `metrics:queries:{region}`]
            rd/tx-queue mut q ['SET' `cache:count:{region}` (mold (len rows))]
            .ok
        ]
    ]
    rows
]

Chapter 7: Shared-Nothing Concurrency, Reactor & Durable Sagas

DURABLE STATE & WORKFLOWS

Crash-Safe Durable Objects & Replay-Safe Workflows over db/kv

Single-writer transactional actors, memoized step checkpoints, external signals, and LIFO saga compensations.

Interactive SVG • Click any node (5 components)
LIB/DURABLE/OBJECT.VK Transactional Keyed Actors LIB/DURABLE/WORKFLOW.VK Deterministic Checkpoint Replay LIB/DB/KV.VK STORAGE LAYER CRC-32 Append-Only WAL do:<ns>:<id> alarm / inbox keys wf:<run>:step evt / comp keys step-done? + mutate Stateful Actor Durable Object Turn open-object + atomic mutate Actor Timers & Mail Alarms & FIFO Inbox set-alarm + enqueue / drain Replay Engine Memoized Workflow Steps start + step + step-with-retry Coordination & Rollback Signals, Timers & LIFO Sagas wait-event + run-compensations Durable Storage CRC-32 Log-Structured KV pwrite + fsync + compact
Components:
Stateful Actor
Durable Object Turn
lib/durable/object.vk
Component 1 of 5
Architectural Role & Purpose

Encapsulates strongly consistent per-entity state keyed by namespace and object ID.

Contextual Description & System Interaction

Models wallets, tenant quotas, device twins, and shopping carts safely.

Core Functionality & Mechanics
  • dobj/mutate snapshots fields and commits atomically on success
  • Automatically rolls back all in-flight mutations if closure returns err
  • Monotonic version counter tracks every committed state transition
Actor Timers & Mail
Alarms & FIFO Inbox
lib/durable/object.vk
Component 2 of 5
Architectural Role & Purpose

Persists scheduled wakeups and ordered actor messages inside the same WAL store.

Contextual Description & System Interaction

Eliminates external Redis/RabbitMQ dependencies for stateful edge services.

Core Functionality & Mechanics
  • poll-due-alarms discovers objects whose deadline <= now_ms
  • enqueue appends durable messages that survive process restarts
  • drain-inbox processes and acknowledges queued work atomically
Replay Engine
Memoized Workflow Steps
lib/durable/workflow.vk
Component 3 of 5
Architectural Role & Purpose

Executes multi-step business processes that resume from their exact last checkpoint after a crash.

Contextual Description & System Interaction

Turns fragile distributed orchestrations into straight-line Veko code.

Core Functionality & Mechanics
  • Completed steps return cached JSON/VBIN results without re-running side effects
  • step-with-retry records attempt counts and exponential backoff
  • Appends an immutable audit trail retrievable via wf/history
Coordination & Rollback
Signals, Timers & LIFO Sagas
lib/durable/workflow.vk
Component 4 of 5
Architectural Role & Purpose

Suspends workflows cleanly on external webhooks/timers and unwinds failures in reverse order.

Contextual Description & System Interaction

Guarantees clean financial and provisioning rollbacks when downstream steps fail.

Core Functionality & Mechanics
  • wait-event returns .waiting until send-event persists the signal
  • sleep-until suspends execution across restarts without holding threads
  • record-compensation & run-compensations execute LIFO saga undo steps
Durable Storage
CRC-32 Log-Structured KV
lib/db/kv.vk
Component 5 of 5
Architectural Role & Purpose

Persists object fields, alarms, workflow steps, signals, and sagas in one crash-safe file.

Contextual Description & System Interaction

Works identically on VM, Wasm (--allow-fs), and all 4 Native OS/CPU targets.

Core Functionality & Mechanics
  • Every record carries a CRC-32 checksum over key + value bytes
  • Recovery truncates partial tail frames automatically on open
  • put-sealed encrypts sensitive credentials with AES-256-GCM

Recipe 7.1: Shared-Nothing Worker Pool with Bounded Channels & Timeouts

Veko eliminates data races by construction: spawn blocks cannot capture outer mut bindings or .secret values, communicating exclusively over typed channels:

VEKO
parallel-checksums = fn [payloads block[bytes]] block[i64] [
    ch = chan/new (len payloads)
    mut tasks = []
    for [idx buf] payloads [
        b_copy = buf
        i_copy = idx
        push mut tasks (spawn [
            chan/send ch { idx = i_copy, size = (len b_copy) }
            .ok
        ])
    ]
    mut sizes = []
    mut received = 0
    while received < (len payloads) [
        msg = chan/recv/timeout/or ch 3s [ { idx = -1, size = 0 } ]
        push mut sizes msg.size
        received = received + 1
    ]
    for [_ t] tasks [ _ = task/await t ]
    sizes
]

Recipe 7.2: Crash-Safe Replayable Saga Workflows, Worker Leases & Dead-Letter Queues (lib/durable/workflow.vk)

Build multi-step payment, provisioning, or deployment workflows where completed steps replay from db/kv after a process crash, non-blocking RetryPolicy steps route exhausted runs to wf_dlq/*, and unrecoverable failures run LIFO saga compensations automatically:

VEKO
use [d = durable, wf = durable/workflow]

run-order-saga = fn [db_path str, order_id str] any [
    mut db  = d/open-store db_path
    defer [ _ = d/close-store mut db ]
    mut run = d/workflow mut db order_id 'fulfill-order' { order_id = order_id }

    policy = wf/RetryPolicy {
        max_attempts   = 3
        base_backoff   = 100ms
        max_backoff    = 2s
        backoff_factor = 2
        dead_letter    = true
    }

    // Step 1: Memoized inventory reservation + LIFO compensation registration
    rsv_id = wf/step-policy/or mut db mut run 'reserve-inventory' policy fn [attempt] [
        'rsv_901'
    ] [e ->
        return (err `reserve failed: {mold e}`)
    ]
    _ = wf/record-compensation mut db mut run 'release-inventory' rsv_id

    // Step 2: Ledger capture — unwinds registered compensations in LIFO order on failure
    rcpt = wf/step-policy/or mut db mut run 'capture-ledger' policy fn [attempt] [
        'rcpt_442'
    ] [e ->
        _ = wf/run-compensations mut db mut run fn [comp_name payload] [
            println `Compensated {comp_name}: {mold payload}`
            .ok
        ]
        return (err `ledger failed: {mold e}`)
    ]

    wf/complete mut db mut run { reservation = rsv_id, receipt = rcpt }
]

Chapter 8: Homoiconic Mini-DSLs, Studio Desktop UI, TUI & Wasm Plugins

TERMINAL, DESKTOP UI & FFI

Capability-Isolated Terminal UI, RGBA32 Canvas, .ui Window & Opt-In .ffi

Four clean layers keeping CLI binaries tiny while enabling rich TrueColor TUIs, 60 FPS 2D GUIs, and C/Rust interop.

Interactive SVG • Click any node (5 components)
ZERO-CAP PURE-VEKO RENDERING Works on VM, Wasm & Native CAPABILITY-GATED OS & FOREIGN BOUNDARIES .ui and opt-in .ffi mut cv present-canvas RGBA32 pixels Shared telemetry Terminal UI Double-Buffered TUI lib/tui.vk (TrueColor ANSI) 2D Rasterizer RGBA32 Software Canvas lib/ui/canvas.vk (Zero-Copy) Widget Toolkit Immediate-Mode Widgets lib/ui/widgets.vk OS Window (.ui) .ui Window Surface lib/ui.vk + --gui PE switch Foreign Interop (.ffi) Opt-In .ffi C-ABI Bridge lib/ffi.vk (Zero-W^X AOT)
Components:
Terminal UI
Double-Buffered TUI
lib/tui.vk
Component 1 of 5
Architectural Role & Purpose

Renders flicker-free terminal dashboards by emitting ANSI escapes only for changed cells.

Contextual Description & System Interaction

Zero ncurses dependency across Windows Terminal, Linux, and macOS.

Core Functionality & Mechanics
  • Boxes, tables, sparklines, progress bars, and interactive menus
  • tui/parse-key decodes CSI arrows, function keys, Ctrl, and UTF-8
  • tui/render-plain emits deterministic snapshots for CI tests
2D Rasterizer
RGBA32 Software Canvas
lib/ui/canvas.vk
Component 2 of 5
Architectural Role & Purpose

Draws alpha-blended shapes, gradients, lines, and crisp 5x7 ASCII glyphs into mut cv.pixels.

Contextual Description & System Interaction

Runs pixel-identically on Native desktops, VM, and Wasm (--check-slabs).

Core Functionality & Mechanics
  • In-place field loans keep rc == 1 with zero CoW buffer copies
  • Porter-Duff SRC_OVER alpha blending, rounded rects, circles
  • Exports uncompressed 24-bit BMP and PPM screenshots directly
Widget Toolkit
Immediate-Mode Widgets
lib/ui/widgets.vk
Component 3 of 5
Architectural Role & Purpose

Composes responsive layouts, themes, hit-tested buttons, lists, and charts over Canvas.

Contextual Description & System Interaction

Clean functional immediate-mode UI with zero retained widget-tree memory leaks.

Core Functionality & Mechanics
  • vstack / hstack layout splitters + Light & Dark Theme palettes
  • Mouse hover/click state machine (UiState + apply-mouse)
  • panel, button, progress-bar, sparkline, and list-view
OS Window (.ui)
.ui Window Surface
lib/ui.vk native_pal5.vk
Component 4 of 5
Architectural Role & Purpose

Blits RGBA32 canvases to native Win32 GDI windows or validated headless surfaces.

Contextual Description & System Interaction

Builds 100 KB–scale self-contained desktop utilities without Electron bloat.

Core Functionality & Mechanics
  • Win64 loads user32/gdi32 ONLY when .ui is imported; --gui hides console
  • Non-blocking ui/poll delivers mouse down/up/move, key, and close events
  • VEKO_HEADLESS=1 & .secret firewall verified on all runtimes
Foreign Interop (.ffi)
Opt-In .ffi C-ABI Bridge
lib/ffi.vk native_pal5.vk
Component 5 of 5
Architectural Role & Purpose

Loads C, C++, Rust, Zig, or Go shared libraries (.dll/.so/.dylib) via static trampolines.

Contextual Description & System Interaction

Connects Veko to specialized GPU, audio, or vendor SDKs without sacrificing W^X.

Core Functionality & Mechanics
  • Denied by default; enabled via --allow-ffi or allow-caps = [.ffi]
  • Deterministic pack/unpack helpers for C structs and NUL strings
  • Blocked on --wasm and guarded against .secret exfiltration

Recipe 8.1: Building a Custom Homoiconic [ ... ] Policy Dialect (quote, compose & parse-block)

Because Veko code and data share the exact same token representation, you can design expressive domain-specific languages in ~20 lines without writing a lexer:

VEKO
eval-acl-rules = fn [rules block, req_role str, req_path str] enum [
    mut i = 0
    while (i + 3) <= (len rules) [
        action = rules[i]       // .allow or .deny
        role   = rules[i + 1]   // 'admin' or '*'
        prefix = rules[i + 2]   // '/admin'
        role_ok = role == '*' or role == req_role
        path_ok = (len req_path) >= (len prefix) and req_path[0..(len prefix)] == prefix
        if role_ok and path_ok [ return action ]
        i = i + 3
    ]
    .deny
]

policy = quote [
    .allow 'superadmin' '/admin'
    .allow '*'          '/stdlib'
    .deny  '*'          '/downloads'
]

decision = eval-acl-rules policy 'guest' '/stdlib/index.html'   // .allow

Recipe 8.2: Official veko-lang.org Ecosystem Packages & Signed VKP1 Bundles

Search, inspect, and install any of the 30 official Ed25519-signed libraries from https://veko-lang.org/packages (cloud_s3, data_formats, openapi, smtp_mail, webauthn, grpc_proto, cluster_raft, mq_streams, db_drivers, resilience, ai_mcp, ai_llm, vec_rag, dataframe_parquet, payments_ledger, graphql, browser_cdp, ldap_saml, oci_k8s, noise_tunnel, iac_fleet, wasm_plugin_sdk, crdt_sync, iot_mqtt, web_live, jobs_cron, doc_media, http_router, veko_ui_kit, sqlite_orm_ext) or pack your own VKP1 archive (lib/pkg/vkp.vk):

POWERSHELL
veko pkg search rag
veko pkg info vec_rag
veko pkg add vec_rag@1.0.0
veko pkg add payments_ledger@1.0.0
veko pkg add graphql@1.0.0
veko pkg verify-lock
VEKO
use [vkp = pkg/vkp, x25 = crypto/x25519, sha = crypto/sha256]

pack-signed-library = fn [] bytes [
    seed = sha/sha256 (bytes/from-str 'publisher-signing-seed-v1')
    pk   = x25/ed25519-pubkey seed
    raw  = vkp/pack-ed25519
        { name = 'veko_ui_kit', version = '1.0.0' }
        { 'mod.vk' = 'pub pill = fn [txt str] str [ `[ {txt} ]` ]' }
        seed
    _ = vkp/verify raw [(vkp/format-trust-key .ed25519 pk)]
    raw
]

Recipe 8.3: Light-Mode Studio UI with Tab Focus Ring, Code Editor & Command Palette (lib/ui/widgets.vk)

Render deterministic RGBA32 Studio surfaces (Win32, zero-libc Linux Wayland/X11, macOS arm64, Wasm <canvas>, or PNG snapshots) with Tab/Shift+Tab keyboard focus traversal, Veko syntax-highlighted code-editor (with 64-step undo/redo), and fuzzy command-palette:

VEKO
use [cv = ui/canvas, w = ui/widgets]

render-studio-frame = fn [mut c cv/Canvas, mut st w/UiState, mut ed w/EditorState, mut pal w/PaletteState] str [
    th = w/light-theme
    cv/clear mut c th.bg
    w/begin-frame mut st

    body = w/panel mut c (w/Rect { x = 16, y = 16, w = 768, h = 448 }) 'Studio Scratchpad' th
    w/code-editor mut c mut st 'main-editor' body mut ed th

    chosen = w/command-palette mut c mut st 'cmd-pal' mut pal [
        w/CommandItem { id = 'run',   label = 'Run Active Module', shortcut = 'Ctrl+Enter' }
        w/CommandItem { id = 'check', label = 'Strict Type Check', shortcut = 'Ctrl+Shift+B' }
    ] th
    w/end-frame mut st
    chosen
]

Recipe 8.4: Fuel-Bounded WebAssembly Sandboxes & Zero-Toolchain Cross-Compilation

Execute untrusted .vk tenant scripts inside vvm with deterministic instruction fuel, or cross-compile standalone native binaries from any host OS:

POWERSHELL
# Run an untrusted plugin in WebAssembly 3.0 with bounded fuel & slab leak verification
veko run --wasm --fuel=500000 --mem-pages=32 --check-slabs plugins/tenant_rule.vk

# Cross-compile standalone native binaries for Windows ARM64, Linux x86_64, Linux ARM64, or Apple Silicon
veko compile --native --target=win-arm64   src/main.vk -o dist/service-win-arm64.exe
veko compile --native --target=linux-x64   src/main.vk -o dist/service-linux-x64
veko compile --native --target=linux-arm64 src/main.vk -o dist/service-linux-arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/service-macos-arm64