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

Veko 1.0 — Master End-User, Standard Library, Systems & Operations Handbook

Veko Language and Runtime


Part I: Veko 1.0 — Overview & Quickstart

Veko (.vk source, fixed-width 64-bit .vko portable bytecode, .wasm WebAssembly 3.0 modules, and standalone native executables across 5 zero-dependency OS/CPU targets: win-x64 PE32+, win-arm64 PE32+ 0xAA64, linux-x64 ELF64, linux-arm64 ELF64, and macos-arm64 Mach-O) is a 100% self-hosted homoiconic systems and dialect programming language (https://veko-lang.org) designed to read like clear human commands, reclaim memory deterministically without a garbage collector, and execute across three backends built in pure .vk (src/, 46 modules) paired with an embedded 95-module pure-.vk standard library (lib/).

Eko Inspecting Veko's Three Execution Tracks


Why Veko Exists

Most programming languages force an uncomfortable trade-off between low-level control (C, C++, Rust, Zig with heavy punctuation or lifetime annotations), everyday ergonomics (Python, Go, Ruby, TypeScript with stop-the-world garbage collection pauses), and syntactic extensibility (Lisp and Forth with parenthesis soup or manual stack shuffling). Veko unifies all three:

  1. Parentheseless Prefix Words + Infix Math: Call fixed-arity words left-to-right (os/write-file path data) while keeping natural infix arithmetic ((crc >>> 8) ^ table[i]), tight dot chains (raw.trim.lower), and slices (buf[0..n]).
  2. Deterministic ORO + Copy-on-Write Memory: Every heap value has a single owner (rc == 1) and frees deterministically at scope exit. Shared snapshots clone lazily only if mutated, and reference cycles are structurally impossible.
  3. Slash Refinements, Zero nil, and /or Recovery: Veko 1.0 has no nil. Unit actions evaluate to .ok, JSON null maps to .null, and missing lookups or I/O failures return catchable err values handled inline via /or [ fallback ] and LIFO defer.
  4. Homoiconic [ ... ] Dialects & Capability Security: Code and data share the same block representation (quote, compose, macro, parse-block), while veko.vk allow-caps and compile-time/runtime .secret firewalls prevent unauthorized syscalls and credential leaks.
UNIFIED COMPILER & RUNTIMES

Veko 1.0 Shared Frontend & Three-Track Execution Pipeline

39 compiler modules (src/) and 79 stdlib modules (lib/) feeding 64-bit VKO VM, Wasm 3.0 sandbox, and 4 native OS/CPU targets.

Interactive SVG • Click any node (11 components)
SHARED PURE-VEKO FRONTEND lexer.vk + parser.vk + macro_eval.vk + types.vk 79-MODULE PURE-VEKO STDLIB lib/* (shared across all 3 tracks) TRACK A: 64-BIT VKO VM vko_emit.vk + oro_vm.vk TRACK B: WASM 3.0 SANDBOX codegen.vk + runtime*.vk + vvm TRACK C: NATIVE X86_64 & AARCH64 native_emit.vk + arm64_emit.vk Tokens + tight RawBlock Expanded AST use DAG 64-bit VKO PAL calls Typed AST .wasm Typed AST Machine code Frontend Whitespace Lexer [tight] vs [spaced] Frontend Two-Pass Pratt Parser arity scan + BP 80..0 Metaprogramming Homoiconic Dialect Pass quote / compose / parse-block Static Analysis Gradual Types & Caps types.vk + .secret audit Standard Library 79-Module Standard Library PQC + Reactor + Web + DB + UI Track A 64-Bit VKO Bytecode VM superinstructions + REPL Track A Host Guarded VM Host PAL VmPolicy + offscreen UI Track B Wasm 3.0 Code Generator linear-RAM ORO + bulk mem Track B Host vvm Zero-Trust Sandbox WASI 0.3 + fuel + SSRF guard Track C x86_64 & AArch64 AOT SIMD + 79-group DCE Track C Linkers PE32+ / ELF64 / Mach-O win-x64, linux, macos-arm64
Components:
Frontend
Whitespace Lexer
lexer.vk
Component 1 of 11
Architectural Role & Purpose

Tokenizes kebab-case words, slash paths, enums, unit literals, and attachment flags.

Contextual Description & System Interaction

Produces an exact token stream carrying source spans and whitespace attachment bits.

Core Functionality & Mechanics
  • Single-pass O(n) scan with 1-byte lookahead
  • Marks tight postfix attachment for xs[i] and user.name
  • Separates n - 1 subtraction from n-1 identifier and -1 literal
Frontend
Two-Pass Pratt Parser
parser.vk
Component 2 of 11
Architectural Role & Purpose

Resolves top-level arities and module aliases in Pass 1, then builds the AST in Pass 2.

Contextual Description & System Interaction

Unifies parentheseless prefix calls with infix arithmetic and left-to-right \ pipes.

Core Functionality & Mechanics
  • Supports order-independent fn, struct, def, and use bindings
  • Preserves homoiconic [ ... ] RawBlocks alongside AST nodes
  • Enforces Pratt binding power ladder from tight postfix (80) to statements (0)
Metaprogramming
Homoiconic Dialect Pass
macro_eval.vk
Component 3 of 11
Architectural Role & Purpose

Expands compile-time macros and structural block dialects before code generation.

Contextual Description & System Interaction

Enables domain mini-languages (RBAC policies, wire schemas, HTML5 trees) in pure Veko.

Core Functionality & Mechanics
  • Splices evaluated expressions into quoted blocks via compose
  • Matches grammar rules over raw token blocks via parse-block
  • Zero runtime interpreter overhead for expanded static macros
Static Analysis
Gradual Types & Caps
types.vk
Component 4 of 11
Architectural Role & Purpose

Checks gradual/strict types, generics [T], mut loans, .secret sinks, and veko.vk allow-caps.

Contextual Description & System Interaction

Guarantees identical static safety invariants across VM, Wasm 3.0, and Native AOT.

Core Functionality & Mechanics
  • Verifies struct schemas, sealed boundaries, and mut field borrows
  • Blocks .secret flows to net, disk, JSON, channels, UI, and FFI
  • Audits workspace path confinement and VKP1 trust-keys
Standard Library
79-Module Standard Library
lib/*
Component 5 of 11
Architectural Role & Purpose

Delivers codecs, NIST FIPS 203/204/205 PQC, TLS 1.3, HTTP/2, Reactor, Durable Workflows, DBs, and TUI/2D UI.

Contextual Description & System Interaction

Gives Veko complete batteries-included capabilities with deterministic ORO memory.

Core Functionality & Mechanics
  • Zero external C/OpenSSL DLL dependencies for core networking and crypto
  • Uses bytes/with-secret and crypto/seal for scoped key hygiene
  • Compiles directly alongside application modules on every backend
Track A
64-Bit VKO Bytecode VM
vko_emit.vk oro_vm.vk
Component 6 of 11
Architectural Role & Purpose

Executes fixed-width 64-bit VKO instructions, interactive REPL sessions, and .vko bundles.

Contextual Description & System Interaction

Ideal for sub-millisecond startup, live REPL exploration, doctests, and tooling.

Core Functionality & Mechanics
  • op:u8 | flags:u8 | a:u16 | bx:u32 word removes 8/16-bit local limits
  • Fused superinstructions accelerate tight loops without JIT RWX pages
  • TRY_OR and DEFER_PUSH frames drive /or recovery and LIFO cleanup
Track A Host
Guarded VM Host PAL
oro_vm.vk
Component 7 of 11
Architectural Role & Purpose

Enforces runtime capability flags (--allow-fs, --allow-net) and .secret sink checks.

Contextual Description & System Interaction

Keeps interactive execution safe by default with explicit capability opt-in.

Core Functionality & Mechanics
  • Isolates spawn worker heaps with deep-frozen value captures
  • Provides readiness reactor polling and validated offscreen UI surfaces
  • Zero GUI DLL or libc bloat inside the compiler binary
Track B
Wasm 3.0 Code Generator
codegen.vk wasm_enc.vk
Component 8 of 11
Architectural Role & Purpose

Emits standalone WebAssembly 3.0 modules with embedded 12-bucket ORO slab allocators.

Contextual Description & System Interaction

Compiles Veko apps and untrusted plugins into portable capability-audited .wasm.

Core Functionality & Mechanics
  • Lowers /or via structured try_table and tail recur via return_call
  • Uses bulk memory.copy and memory.fill for fast buffer operations
  • Exports _oro_live_slabs for mathematical zero-leak verification
Track B Host
vvm Zero-Trust Sandbox
runtime*.vk
Component 9 of 11
Architectural Role & Purpose

Runs Wasm modules under deterministic fuel quotas, memory caps, and host sandboxes.

Contextual Description & System Interaction

Designed for multi-tenant plugin execution and deterministic compliance workloads.

Core Functionality & Mechanics
  • Enforces per-directory FS confinement and private-IP SSRF blocking
  • Strictly forbids .ffi foreign library loading inside Wasm
  • Isolates concurrent workers in separate linear-memory stores
Track C
x86_64 & AArch64 AOT
native_emit.vk arm64_emit.vk
Component 10 of 11
Architectural Role & Purpose

Compiles directly to native x86_64 and ARM64 machine code with zero external toolchain.

Contextual Description & System Interaction

Delivers maximum throughput and sub-millisecond cold starts without a GC or JIT.

Core Functionality & Mechanics
  • Runtime CPUID dispatch for AVX2, SSE2, and AES-NI intrinsics
  • 79-group worklist DCE strips unused runtime/UI/FFI helpers
  • Cached veko run --native via SHA-256 content-addressed binaries
Track C Linkers
PE32+ / ELF64 / Mach-O
pe_emit.vk elf_emit.vk macho_emit.vk
Component 11 of 11
Architectural Role & Purpose

Links standalone executables for Windows x64, Linux x64/arm64, and Apple Silicon.

Contextual Description & System Interaction

Cross-compiles any target from any host OS in a single command.

Core Functionality & Mechanics
  • Win64 PE32+ (--gui Subsystem=2), static zero-libc Linux ELF64
  • 16 KiB page-aligned macOS arm64 Mach-O + SHA-256 LC_CODE_SIGNATURE
  • Triple-target S1 == S2 self-hosting bit-identical convergence

Three Execution Tracks: Purpose & Decision Guide

All three execution tracks share the exact same lexer, Pratt parser, type/capability checker, ORO ownership rules, and 95-module lib/ standard library (embedded directly inside the single-binary veko SDK):

EXECUTION MODES

Choosing Between Veko's Three Execution Tracks

Write idiomatic .vk code once and select the runtime envelope matching development speed, isolation, or native deployment.

Interactive SVG • Click any node (5 components)
SOURCE WORKSPACE veko.vk + src/*.vk RUNTIME & DEPLOYMENT ENVELOPES Identical ORO & .secret semantics --vm (default) --wasm --native .wasm PE / ELF / Mach-O Source Veko Source & Manifest veko check --strict-types Development Track A: ORO Bytecode VM veko run app.vk / veko repl Zero-Trust Track B: Wasm 3.0 Sandbox veko run --wasm --fuel=... Production Track C: Native Machine Code veko compile --native Delivery Shipped Artifacts .exe / ELF64 / Mach-O / .vkp
Components:
Source
Veko Source & Manifest
main.vk types.vk
Component 1 of 5
Architectural Role & Purpose

Single source of truth defining module imports, types, and capability declarations.

Contextual Description & System Interaction

Every Veko program starts from the same clean module graph.

Core Functionality & Mechanics
  • Checked once by veko check and formatted by veko fmt
  • Declares allow-caps = [.fs .clocks .env .net .ui] in veko.vk
  • Zero #ifdef soup across VM, Wasm 3.0, and Native targets
Development
Track A: ORO Bytecode VM
oro_vm.vk
Component 2 of 5
Architectural Role & Purpose

Fastest edit-run-test cycle, interactive REPL, and portable .vko bytecode bundles.

Contextual Description & System Interaction

Use Track A during daily coding, scripting, and interactive debugging.

Core Functionality & Mechanics
  • Instant startup with zero link wait
  • Supports dynamic eval and interactive :stats inspection
  • Default engine for veko doc --test
Zero-Trust
Track B: Wasm 3.0 Sandbox
codegen.vk
Component 3 of 5
Architectural Role & Purpose

Deterministic capability-confined execution for untrusted extensions and CI leak audits.

Contextual Description & System Interaction

Use Track B for multi-tenant plugins, reproducible sandboxes, and slab leak verification.

Core Functionality & Mechanics
  • Enforces --fuel instruction budgets and --mem-pages ceilings
  • --check-slabs proves _oro_live_slabs == 0 on exit
  • Blocks .ffi and confines filesystem roots
Production
Track C: Native Machine Code
native_emit.vk arm64_emit.vk
Component 4 of 5
Architectural Role & Purpose

Standalone zero-GC executables with SIMD acceleration and cross-OS compilation.

Contextual Description & System Interaction

Use Track C for production servers, CLI tools, desktop GUIs, and edge appliances.

Core Functionality & Mechanics
  • veko run --native caches compiled binaries by SHA-256
  • Emits win-x64 PE32+, linux-x64/arm64 static ELF64, macos-arm64 Mach-O
  • Supports --gui console-free windows and opt-in --allow-ffi
Delivery
Shipped Artifacts
pe_emit.vk elf_emit.vk macho_emit.vk
Component 5 of 5
Architectural Role & Purpose

Self-contained binaries and Ed25519/ML-DSA signed VKP1 source bundles.

Contextual Description & System Interaction

Deploy tiny self-contained artifacts anywhere from cloud VMs to ARM64 edge nodes.

Core Functionality & Mechanics
  • Zero external runtime, JVM, or garbage collector required
  • Single-file copy deployment to containers or bare metal
  • Cryptographically verifiable supply chain via veko pkg
Decision Criteria Track A: --vm / .vko Track B: --wasm (vvm) Track C: --native (x86_64 & arm64)
Primary Goal Instant run, live REPL & .vko bundles Zero-trust isolation & leak verification Standalone OS binaries with zero runtime deps
Targets Cross-platform 64-bit VKO VM WebAssembly 3.0 + WASI 0.3 (vvm) win-x64, win-arm64, linux-x64, linux-arm64, macos-arm64
Sandbox & Quotas --fuel, --allow-fs, --allow-net, --allow-listen, --allow-private-net Full HostSandbox (--fuel, --mem-pages, --check-slabs, FS chroot, SSRF guard) Compile-time veko.vk allow-caps + runtime .secret firewall
Networking & UI lib/net/client, lib/web, lib/reactor, lib/tui, offscreen .ui WASI sockets/net-poll + lib/web, lib/tui, offscreen .ui (.ffi forbidden) Full OS sockets/DNS/TLS 1.3, epoll/kqueue/IOCP, live Win32 --gui, opt-in .ffi

Meet Eko — The Veko Mascot

Eko the Galago — Veko Language Mascot

Veko's mascot is Eko, a silver-taupe Galago (bush baby):

  • Why a Galago named Eko? Eko plays on echo—the clean reflection of homoiconic [ ... ] blocks and compile-time dialects that turn domain notation directly into native code—paired with V to form Veko.
  • Oversized Amber Eyes & Inspectability: A bush baby sees clearly in the dark without guesswork, mirroring Veko's explicit mut loans and built-in token, AST, module, and bytecode inspectors (veko inspect).
  • Independent Acoustic Ears & Refinements: Galagos swivel each ribbed ear to isolate exact signals; Veko's slash refinements (/timeout, /secret, /or) and parse-block rules compose behavior cleanly at the call site.
  • Nimble Single-Branch Balance (ORO + CoW): Agile and lightweight, a Galago lands cleanly on one branch at a time—just as One Reference Only keeps a single owner per value and reclaims memory deterministically without GC pauses.

End-User Documentation Reading Path

Order & Guide Audience What You Will Learn
01. Overview & Quickstart (this page) Everyone Core pillars, execution tracks, and first commands
02. Full Tutorial New Learners 9 hands-on lessons from REPL & pipes through macros, spawn, and structs
03. Language Guide Developers Complete guide to syntax, whitespace rules, ORO memory, closures, and dialects
04. How-To & Newcomer Guide Newcomers & Devs 5 pointers on how to read/write Veko, token/AST inspection, and project recipes
04b. Cookbook & Language Comparisons Evaluators & Devs Idiomatic recipes plus Readability & Writability vs. Go, Rust, Zig, Elixir/Rebol, and Python/TS
05. Developer Tooling All Engineers veko debug & VS Code F5 DAP, veko test --coverage, testing/fuzz, veko fmt, veko lsp, veko doc --html, SVG flamegraphs, veko-lang.org packages, and migrators
06. Standard Library & PQC App & Crypto Devs Complete 95-module stdlib index, collections, codecs, classical crypto, and NIST FIPS 203/204/205 PQC
07. Net, Web, DB & VKP1 Backend & Web Devs io/Stream, DNS, Hybrid PQC TLS 1.3, HTTP/2, QUIC HTTP/3, WebSockets, web + html, JWT/OAuth2/TOTP, Zero-FFI SQLite 3 & ORM (db/sqlite), db/*, and veko-lang.org VKP1 packages
08. Async I/O & Reactor Systems Devs epoll/kqueue/IOCP readiness reactor, timers, cross-thread wakers, web/serve-reactor, and batch HTTP
09. Durable Objects & Workflows Distributed Devs Crash-safe Durable Objects and replay-safe Durable Workflows with LIFO sagas over db/kv
10. TUI, Native UI & FFI Desktop & C/Rust Devs Diffing ANSI tui, 29-widget RGBA32 desktop UI, Win32 + Linux Wayland/X11 + macOS arm64 Cocoa + Wasm <canvas>, clipboard/Hi-DPI, and .ffi (VEKO_LIB)
11. Perf, SIMD & ARM64 Systems Engineers Zero-JIT philosophy, AVX2/SSE2/AES-NI, cached veko run --native, and win-arm64/linux-arm64/macos-arm64
12. Examples & Showcase Apps All Engineers Walkthrough of all 45 examples (01..40 + core tours) and 6 multi-module demos/ apps
13. Administrator Guide Operators & SecOps Build governance, allow-caps, vvm HostSandbox quotas, VKP1 trust-keys, and .secret wiping
14. CLI & Syntax Reference All Users Complete CLI subcommands & flags, veko.vk schema, Pratt precedence ladder, and 105+ builtin arities
15. Master User Handbook All Users Consolidated single-page edition of all End-User guides

Zero-Install Playground & One-Line SDK Installation

Try Veko instantly in your browser (client-side WebAssembly 3.0 Web Worker + <canvas> + sandboxed 64-bit VKO VM) at https://veko-lang.org/play, or install the single-binary portable SDK on Linux, macOS Apple Silicon, or Windows (x86_64 and native Windows 11 ARM64 — Snapdragon X Elite/Plus, Surface Pro/Laptop, and Windows on ARM VMs):

BASH
# Linux (x86_64 / arm64) and macOS (Apple Silicon arm64) — SHA-256 verified
curl -fsSL https://veko-lang.org/install.sh | sh
POWERSHELL
# Windows (PowerShell — auto-detects x64 vs. ARM64 and installs veko-1.0.0-win-x64.zip or veko-1.0.0-win-arm64.zip)
irm https://veko-lang.org/install.ps1 | iex

Offline .zip SDK archives (veko-1.0.0-win-x64.zip for Windows x86_64 PE32+ and veko-1.0.0-win-arm64.zip for native Windows 11 ARM64 PE32+ 0xAA64, bundling veko.exe, lib/, examples/, AGENTS.md, README.md, and LICENSE) are also available at https://veko-lang.org/download.


Quickstart Commands

POWERSHELL
# Verify all 18 test suites or run the full S1 == S2 build orchestrator
veko run tests/run_tests.vk
veko run build.vk -- all

# Run programs across ORO VM (--vm), Wasm 3.0 (--wasm), or cached Native (--native)
veko run examples/hello.vk
veko run --wasm --check-slabs examples/09_concurrent_worker_pool.vk
veko run --native examples/29_async_reactor_http_server_and_client.vk
veko run --native examples/32_durable_objects_and_workflows.vk

# Cross-compile standalone native binaries for all 5 zero-dependency OS/CPU targets
veko compile --native --target=win-x64     examples/14_http_json_api_server.vk -o dist/api.exe
veko compile --native --target=win-arm64   examples/hello.vk -o dist/hello_win_arm64.exe
veko compile --native --target=linux-x64   examples/hello.vk -o dist/hello_linux_x64
veko compile --native --target=linux-arm64 examples/hello.vk -o dist/hello_linux_arm64
veko compile --native --target=macos-arm64 examples/hello.vk -o dist/hello_macos_arm64

# Run multi-module showcase applications (Web, Desktop GUI, Multi-Protocol Mesh, PQC Vault)
veko run --native demos/taskflow_studio/src/main.vk
veko run --native demos/canvas_workbench/src/main.vk
veko run --native demos/pulse_mesh/src/main.vk
veko run --native demos/vault_dialect/src/main.vk

# Launch the interactive REPL or regenerate HTML documentation
veko repl
veko docs

Part II: Full Veko Language Tutorial

This hands-on tutorial walks through everything you can write and run in Veko today using veko check, veko run, veko compile, veko repl, and veko inspect.


Lesson 1: Running Programs, Inspecting Code, and the REPL

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

Start by running an existing example or opening the interactive ORO REPL:

POWERSHELL
# Run a Veko script on the ORO bytecode VM
veko run examples/01_basics_and_math.vk

# Inspect lexer tokens, Pratt AST, or compiled 64-bit VKO bytecode
veko inspect --tokens examples/01_basics_and_math.vk
veko inspect --ast examples/01_basics_and_math.vk
veko inspect --bytecode examples/hello.vk

# Start the interactive REPL
veko repl

Inside veko repl, bindings persist across lines, multi-line [ ... ] and { ... } blocks balance automatically, and built-in REPL commands let you watch ORO memory live:

  • :stats prints live_slabs, globals, and compiled fns count.
  • :reset clears all globals and slabs back to a clean VM.
  • :quit exits the REPL.

Lesson 2: Bindings, Rich Literals, Math, and Slicing

Veko keeps everyday code on unshifted keys: = binds values, '...' defines UTF-8 strings, .word creates enum symbols, and durations/sizes are native literals (1024-based for byte sizes):

VEKO
// examples/01_basics_and_math.vk
title   = 'Veko Basics'
timeout = 250ms
buf-cap = 4kb
proto   = .tcp

// Spaced infix arithmetic & bitwise ring-buffer indexing
head = 12
offset = 7
cap = 16
next-slot = (head + offset) & (cap - 1)   // 3

// Ranges & tight slicing
nums = 1..=5                              // [1 2 3 4 5]
sub  = nums[1..4]                         // [2 3 4]

// Mutable loop state
mut i = 0
mut sum = 0
while i < 5 [
    i = i + 1
    sum = sum + i
]
println sum                               // 15

unless zero? sum [
    println 'sum-nonzero'
]

Important Spacing Rule: Always put spaces around binary - and / (cap - 1, total / count) so the lexer does not treat them as kebab-case words (read-into) or module paths (str/trim).


Lesson 3: Pipes, UFCS Dot-Chains, JSON, and match

Because every word has a fixed compile-time arity, pipelines flow cleanly from left to right without nested parentheses. Use \ pipes to pass a value as the first argument to the next multi-argument word, and tight . chains for field access or 1-argument transforms:

VEKO
// examples/02_pipelines_and_json.vk
use [j = json, s = strings]

payload = '[{"name": " alpha ", "score": 90, "active": true}, {"name": " beta ", "score": 40, "active": false}, {"name": " gamma ", "score": 85, "active": true}]'

names = payload
    \ j/decode
    \ filter fn [item] [item.active]
    \ map fn [item] [item.name.trim.upper]

println (s/join names ' | ')    // ALPHA | GAMMA

scores = payload
    \ j/decode
    \ filter fn [item] [item.active]
    \ map fn [item] [item.score]

total = reduce scores 0 fn [acc x] [acc + x]
println total                   // 175.0

ev = { kind = .ready, code = 200 }
status-msg = match ev.kind [
    .starting ['booting']
    .ready    ['serving']
    _         ['unknown']
]
println status-msg              // serving

Lesson 4: ORO Buffers, Secrets, defer, /or, and recur

Veko gives you deterministic zero-GC memory through One Reference Only (ORO) rules:

  • bytes/with-cap allocates a reusable byte slab once; mut loans mutate it in place with zero reallocations.
  • bytes/with-secret marks a slab with flag_secret so its contents are overwritten with zero bytes the moment its scope exits.
  • defer [ ... ] runs cleanup blocks in LIFO order when the enclosing function returns.
  • /or [ ... ] catches errors inline on any fallible call (str/index-of/or, os/read-file/or, net/http/fetch/or; note that pure-.vk codec/http1 + net/* works identically across all three tracks including --native).
  • recur performs constant-stack tail recursion back to the top of the current fn.
VEKO
// examples/03_oro_buffers_and_errors.vk
use [bytes, ascii, str]

pkt = bytes/with-cap 4kb
bytes/push-all mut pkt (bytes/from-str '  ping trustnode  ')
ascii/trim-right! mut pkt
ascii/upper! mut pkt
bytes/push mut pkt 33
println (str/from-bytes pkt)      //   PING TRUSTNODE!

use-secret = fn [label] [
    secret = bytes/with-secret 64b
    bytes/push-all mut secret (bytes/from-str 'ephemeral-session-key')
    println (str/append label ':secret-ready')
    secret.len
]
println (use-secret 'auth')       // 21 (and secret slab zeroed on return)

safe-find = fn [hay needle] [
    defer [println 'cleanup-done']
    str/index-of/or hay needle [-1]
]
println (safe-find 'veko-oro-vm' 'oro')      // 5, then cleanup-done
println (safe-find 'veko-oro-vm' 'missing')  // -1, then cleanup-done

gcd = fn [a b] [
    if zero? b [return a]
    recur b (a % b)
]
println (gcd 84 36)               // 12

Lesson 5: Homoiconicity, compose, parse-block, and Macros

Code inside [ ... ] is a live homoiconic list of words, numbers, enums, durations, strings, and nested blocks:

VEKO
// examples/04_macros_and_dialects.vk
spec = quote [route .tcp '10.0.0.0/8' 8443 30s]
println spec.len            // 5
println (type-of spec[1])   // .enum_sym
println spec[4]             // 30s

port = 9000
tls-mode = .strict
server-cfg = compose/deep [
    bind '127.0.0.1' (port)
    policy [mode (tls-mode) timeout 15s]
]
println (mold server-cfg)   // [bind '127.0.0.1' 9000 policy [mode .strict timeout 15s]]

mut endpoints = []
parsed-ok = parse-block (quote [allow .tcp '10.1.0.0/16' 443 allow .udp '10.2.0.0/16' 51820]) [
    any [
        ['allow' proto = enum! cidr = str! p = int!] [
            push mut endpoints (compose [(proto) (cidr) (p)])
        ]
    ]
]
println parsed-ok           // true
println (mold endpoints)    // [[.tcp '10.1.0.0/16' 443] [.udp '10.2.0.0/16' 51820]]

triple = macro [x] [
    compose [(x) + (x) + (x)]
]
println (triple 14)         // 42

Lesson 6: Stateful Closures & Capability Records (No OOP Needed)

Closures capture outer variables into their own private ORO slab—making stateful generators cycle-free and giving you clean runtime polymorphism via explicit records of closures:

VEKO
// examples/05_closures_and_capabilities.vk
use [str]

make-seq = fn [start] [
    mut cur = start
    fn [step] [
        out = cur
        cur = cur + step
        out
    ]
]

next-port = make-seq 8000
println (next-port 10)   // 8000
println (next-port 10)   // 8010
println (next-port 10)   // 8020

make-logger = fn [prefix] [
    {
        info  = fn [msg] [println (str/append prefix msg)]
        warn  = fn [msg] [println (str/append '[WARN] ' msg)]
        flush = fn []    [println (str/append prefix 'flushed')]
    }
]

app-log = make-logger '[veko] '
log-info = app-log.info
log-warn = app-log.warn
(log-info 'initialized') // [veko] initialized
(log-warn 'cache-miss')  // [WARN] cache-miss
call app-log.flush       // [veko] flushed

Lesson 7: Multi-File Projects, pub/export, and veko.vk Manifests

As programs grow, split reusable helpers across logical modules without OS paths or circular imports. Everything in a module stays private by default; export only functions or compile-time macros using pub or export [...]:

VEKO
// src/lib/codec.vk
salt = 7
mask = fn [x] [x ^ salt]       // private helper (cannot be called externally)

pub encode = fn [x] [mask (x * 3)]
wrap-add = macro [a b] [compose [(a) + (b)]]
export [wrap-add]

Add an optional homoiconic veko.vk manifest in your project folder to declare the source root, external dependencies, and least-privilege capability limits:

VEKO
// veko.vk
{
  name = 'edge-app'
  root = 'src'
  allow-caps = [.fs]
}

Then import modules by logical name in your entry file, audit capabilities, and run identically on ORO VM, .vko, WebAssembly 3.0, or standalone native x86_64 & AArch64:

VEKO
// src/main.vk
use [c = lib/codec]
println (c/encode 4)       // 11
println (c/wrap-add 20 22) // 42
println (4 \ c/encode)     // 11
POWERSHELL
# Audit module DAG, exported arities, and effective capabilities
veko inspect --modules src/main.vk

# Run identically across ORO VM, compiled .vko bytecode, Wasm 3.0, or native x86_64 & arm64
veko run src/main.vk
veko compile --vko src/main.vk -o dist/app.vko
veko run dist/app.vko
veko run --wasm src/main.vk
veko run --native src/main.vk
veko compile --native src/main.vk -o dist/app.exe
./dist/app.exe
# Or cross-compile standalone Windows ARM64, Linux x86_64, Linux ARM64, or macOS Apple Silicon binaries
veko compile --native --target=win-arm64   src/main.vk -o dist/app_win_arm64.exe
veko compile --native --target=linux-x64   src/main.vk -o dist/app_lx64
veko compile --native --target=linux-arm64 src/main.vk -o dist/app_arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/app_macos

Lesson 8: Shared-Nothing Concurrency & Guarded Networking

Veko pairs isolated spawn [ ... ] workers with bounded ownership-transfer channels (chan/*) and guarded networking across host OS sockets (--vm), wasi:sockets@0.3.0 / wasi:http@0.3.0 (--wasm), and native WinSock2 / Linux / macOS sockets (--native)—blocking mutable aliasing, data races, .secret network leaks, and SSRF by construction:

VEKO
ch = chan/new 4

worker = spawn [
    chan/send ch 'ready-from-worker'
    42
]

msg = chan/recv ch
res = task/await worker
chan/close ch
println msg   // ready-from-worker
println res   // 42

When running network clients or local servers, grant least-privilege flags explicitly (--allow-net, --allow-listen, --allow-private-net) on veko run (applies to both --vm and --wasm), and declare allow-caps = [.net] inside veko.vk. Standalone --native binaries execute directly as OS processes with .secret egress blocks still enforced at runtime.


Lesson 9: Typed Structs, veko check, Checked Conversions & Secrets

Opt into static types incrementally with struct { ... }, interface { ... }, parameter/return annotations, secret field qualifiers, and checked numeric/string conversions—preserving clean /or fallbacks and cross-backend speed:

VEKO
Upstream = struct {
    name    str
    host    str
    port    i64 = 443
    api_key secret str = ''
}

score-samples = fn [ep Upstream, factor u8, n i64] i64 [
    mut acc = 0
    mut i = 0
    while i < n [
        acc = acc + factor + i
        i = i + 1
    ]
    acc + ep.port
]

parsed-port = str/to-i64/or '8443' [443]
weight      = as-u8/or 12 [as-u8 0]
tok         = os/getenv/secret/or 'API_KEY' ['local-dev-key']

u1 = Upstream { name = 'edge-us', host = 'api.veko.local', api_key = tok }
u2 = u1 \ struct/with { port = parsed-port }
println (score-samples u2 weight 5000)
POWERSHELL
# Static type + secret taint verification across modules
veko check examples/12_typed_structs_and_secrets.vk
veko check --strict-types examples/12_typed_structs_and_secrets.vk

# Execute identically on ORO VM, Wasm 3.0 (unboxed math loops), or native x86_64 / arm64
veko run examples/12_typed_structs_and_secrets.vk
veko run --wasm examples/12_typed_structs_and_secrets.vk
veko run --native examples/12_typed_structs_and_secrets.vk
veko compile --native examples/12_typed_structs_and_secrets.vk -o dist/12.exe
./dist/12.exe
veko compile --native --target=linux-x64   examples/12_typed_structs_and_secrets.vk -o dist/12
veko compile --native --target=linux-arm64 examples/12_typed_structs_and_secrets.vk -o dist/12_arm64

Next Steps

Continue along the End-User reading path:


Part III: End-User Language Guide

This guide introduces Veko's syntax, memory model, closures, homoiconicity, non-OOP composition patterns, and three execution backends.


1. Words, Refinements, and Pipelines

Veko eliminates outer parentheses and commas for normal function calls. Because every word has a fixed compile-time arity, expressions read cleanly from left to right:

VEKO
// Bindings use '=', strings use single quotes, durations and sizes are native literals
timeout = 5s
max-buf = 64kb
mode    = .tls

print 'starting sync'

Slash Refinements

Optional behavior never relies on positional boolean flags or multi-line option structs. Words expose slash refinements that extend static arity at the call site:

VEKO
use [h = net/http, j = json, s = strings, os]

// Base call takes 1 argument (url)
body = h/fetch 'https://example.com/peers'

// Adding /timeout extends static arity to 2 (url, duration)
body = h/fetch/timeout 'https://example.com/peers' 3s

// Universal /or handles errors inline without try/catch pyramids
body = h/fetch/timeout/or 'https://example.com/peers' 3s [
    log/warn 'using cached peer list'
    os/read-file 'peers.cache.json'
]

UFCS Dot-Chains and \ Pipes

  • Tight dot-chains (.) read struct/map fields (peer.endpoint) or chain 1-argument transforms (raw.trim.upper).
  • Pipes (\) inject the left-hand result as the first argument of the next multi-argument word:
VEKO
sync-peers = fn [endpoint out-path] [
    active-urls = h/fetch/timeout endpoint 5s
        \ j/decode
        \ filter fn [p] [p.active]
        \ map fn [p] [p.url.trim]

    os/write-file out-path (s/join active-urls '\n')
    active-urls.len
]

Arithmetic and Tight Indexing

Binary math and bitwise operators work with standard infix precedence when spaced cleanly:

VEKO
crc       = (crc >> 8) ^ table[(crc ^ b) & 0xff]
next-slot = (head + offset) & (cap - 1)
header    = packet[0..16]

2. Deterministic Memory Without a Garbage Collector (ORO + CoW)

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

Veko enforces One Reference Only (ORO) backed by Copy-on-Write (CoW):

  1. Plain Words Borrow for Free: Passing packet to log/debug packet lends read-only access for the call duration—zero copies and zero reference-count updates.
  2. = Moves Ownership: Assigning b = a transfers ownership to b and deterministically frees whatever b previously held.
  3. mut Mutates in Place: Functions may modify an argument in place only when both the parameter and call site carry mut:
VEKO
use [net, bytes, ascii]

echo-session = fn [mut conn] [
    defer [net/close/or mut conn []]

    // Allocated once; freed deterministically when echo-session returns
    mut buf = bytes/with-cap 4kb

    forever [
        n = net/read-into/or mut conn mut buf [break]
        if zero? n [break]

        ascii/trim-right! mut buf
        ascii/upper! mut buf
        bytes/push mut buf 10

        net/write/or mut conn buf [break]
    ]
]

Closures Without Reference Cycles

When a fn captures outer variables, those values move (or CoW-snapshot) into the closure's owned environment block:

VEKO
make-counter = fn [start] [
    fn [step] [
        start = start + step
        start
    ]
]

next-id = make-counter 100
print (next-id 1)   // 101
print (next-id 5)   // 106

Because each closure owns its private environment tree and recursive self-calls use an implicit recur/self word without storing the closure inside its own capture block, reference cycles cannot form.

Higher-Order Functions & Dynamic Closure Calls

Functions in Veko (fn [...] [...]) are first-class values that can be passed to combinators (filter, map, each, reduce), returned from factories, or stored inside capability records:

  • Static-arity bindings call directly: Top-level or local name = fn [a b] [...] bindings have known compile-time arity and call left-to-right without parentheses (name 1 2).
  • Dynamic closure values use (callee arg1 ...) or (f) / call: When invoking a function parameter, returned closure, or record callback whose arity is only known at runtime, wrap the call in parentheses ((next-id 1), (transport.read mut buf), or 0-arg (transport.flush) / call f). Note that spawn blocks reject capturing runtime closures across isolated workers.

"No nil" Discipline, Disjoint Field mut Loans & [T] Generics

Veko 1.0 eliminates nil completely so missing data never silently propagates:

  • Missing Lookups & Empty Pops Return err: map/get m k, m[k], m.k, json/get s k, and empty pop, first, or last return catchable err values handled explicitly with /or (host = map/get/or cfg 'host' ['127.0.0.1']).
  • Explicit .ok & .null Enums: Side-effect actions (print, log/*, time/sleep, net/close, chan/send, os/mkdir), one-armed if expressions, loops, and 0-arg return evaluate to .ok, while JSON null round-trips cleanly via .null (json/decode 'null' == .null).
  • Struct-Field mut Loans (mut ctx.field): Mutable struct bindings can lend disjoint fields directly in place (bytes/push mut state.buf 10, put mut state .count (state.count + 1)) while preserving Copy-on-Write snapshots automatically.
  • Parametric [T] Generics, sealed Structs & /internal/ Modules: Functions and structs support checker-level type parameters (id = fn [T] [x T] T [ x ], pub Box = sealed struct [T] { val T }), sealed struct restricts direct construction and mut field loans to the defining module, and pkg/internal/* modules are confined to importers under pkg/*.

3. Homoiconicity and Compile-Time Dialects

Everything inside [ ... ] is a live homoiconic block of typed values (words, paths, numbers, durations, sizes, enums, strings, and nested blocks).

  • quote [ ... ] preserves a block as unevaluated data.
  • compose [ ... ] walks a block and evaluates only expressions wrapped in ( ... ), avoiding Lisp backtick/comma punctuation soup.
  • parse-block matches structural token patterns (word!, enum!, str!, int!, dur!, block!) inside compile-time macro definitions to lower domain mini-languages directly into static code.

4. Intentional Non-OOP Design

Veko intentionally omits classes, inheritance, and mutable this object graphs because shared mutable identities break ORO determinism and opaque private fields break homoiconicity:

  • Closed Variants: Use tagged unions with match ev.kind [ .ping [...] .data [...] ].
  • Open Pluggability: Pass explicit capability records (Transport { read = fn [mut dst] [...], write = fn [src] [...] }) constructed from ORO closures.

5. Multi-File Modules & Private-by-Default Encapsulation

Veko separates local code organization from public module APIs without ambient filesystem searching or mutable global leaks:

  • Logical Module Paths Only: Imports (use [alias = lib/codec, crypto]) never mention ./, ../, OS path separators, or .vk extensions. Precedence resolves reserved built-ins (bytes, str, json, os, time, log, net, http), then project root, then declared deps in veko.vk.
  • Functions, Macros & Structs (pub / export): All top-level bindings are private by default. Export functions, compile-time macros, and struct schemas (pub encode = fn [...] [...], pub Endpoint = struct { ... }, or export [fn1 macro2 Endpoint]), while forbidding shared mutable globals across modules.
  • Single Diamond Initialization: Shared modules initialize once in topological order with isolated global namespaces, preventing cross-module name collisions even when private helper names match.

6. Shared-Nothing Concurrency & Cross-Backend Networking

Veko extends ORO ownership rules across threads cleanly:

  • Isolated spawn [ ... ] Tasks & Bounded Channels: Each spawned task executes inside its own private ORO arena (oro_vm.vk), isolated Wasm HostSandbox (codegen.vk), or private OS worker thread state (native_emit.vk / arm64_emit.vk). Capturing or mutating outer mut variables across spawn, or sending .secret, mut loans, or closures through chan/send, is rejected deterministically.
  • Explicit Network Capabilities: net/listen-tcp, net/connect-tcp, net/accept, net/read-bytes, net/read-into, net/write, net/write-string, net/resolve, UDP sockets, and the 11 net/poll-* / net/try-* readiness reactor primitives—along with pure-.vk net/dns, net/client, web, codec/http1, net/http2, net/websocket, and Hybrid PQC net/tls13—run across all three backends (oro_vm.vk, codegen.vk, and native_emit.vk / arm64_emit.vk), while host-bridged http/fetch and http/request run on --vm and --wasm. Under veko run (--vm and --wasm), networking stays disabled by default until authorized (--allow-net, --allow-listen, --allow-private-net), and all backends block .secret values on every network sink and enforce SSRF guards.

7. Gradual & Strict Types, O(1) Structs & Secret Flow Governance

Veko keeps zero-annotation scripting effortless while letting critical paths and shared module boundaries opt into static verification and unboxed execution:

  • Typed struct Schemas & struct/with: Define schemas with defaults (Upstream = struct { host str, port i64 = 443, api_key secret str = '' }), verify missing/unknown fields at compile time, read fields directly in O(1), and produce updated snapshots cleanly with primary \ struct/with { port = 8443 }.
  • Checked Narrowing & Runtime Guards: Use str/to-i64, str/to-f64, as-u8, as-i64, and as-f64 paired with /or instead of silent truncation; annotated functions (fn [factor u8, ep Upstream] i64 [...]) enforce runtime entry guards across Veko's execution backends.
  • veko check [--strict-types]: Validate cross-module types, mut borrows, and .secret sink policies statically before running or deploying; os/getenv/secret, redaction to <secret>, and deep .secret blocking on json/encode and os/write-file provide runtime defense in depth.

Designing Safe & Resilient Systems in Veko

Veko combines four built-in guarantees so everyday scripts and production services stay predictable under invalid input, concurrency, and resource pressure:

  • Memory Safe in Everyday .vk Code: Indexing and slicing on bytes, str, block, and struct values are bounds-checked (spatial safety), single-owner ORO + Copy-on-Write (CoW) prevents use-after-free, double-free, and cyclic leaks without GC pauses (temporal safety), and spawn forbids sharing mutable references or closures across threads (data-race freedom).
  • Explicit Error & Cleanup Paths: Division/modulo by zero (/ 0, % 0), integer/float parsing (str/to-i64, str/to-f64), and range narrowing (as-u8) raise catchable /or errors instead of silently truncating or crashing the process. Pair /or with LIFO defer so files, sockets, and buffers always clean up cleanly along both normal and error paths.
  • Schema & Capability Discipline: Enforce required fields and defaults in struct definitions, apply immutable snapshots with struct/with, load credentials via os/getenv/secret (automatic <secret> redaction, egress blocking, and zero-wipe on free), and declare explicit allow-caps in veko.vk audited with veko check --strict-types and veko inspect --modules.

8. Choosing Your Execution Backend

Veko compiles the same .vk source language across three backends—each built for a distinct purpose:

  1. 64-Bit VKO Bytecode VM (--vm / .vko): Created for instant script execution, the interactive veko repl, dynamic eval, and precompiled 64-bit VKO distribution. Ideal for everyday development, doctests, and rapid iteration.
  2. WebAssembly 3.0 Sandbox (--wasm via vvm): Created for zero-trust, portable sandboxing. Compiles .vk programs to validated Wasm 3.0 with unboxed i64/f64 loops and runs inside vvm's HostSandbox with explicit --fuel, --mem-pages, --allow-fs, --allow-hosts, and --check-slabs leak verification.
  3. Native x86_64 & AArch64 (--native via veko): Created for standalone Windows (--target=win-x64 and --target=win-arm64 0xAA64 PE32+, with optional --gui), Linux (--target=linux-x64 and --target=linux-arm64 static ELF64 via direct syscalls), and macOS Apple Silicon (--target=macos-arm64 16 KiB Mach-O + SHA-256 LC_CODE_SIGNATURE) executables with zero external C compiler, LLVM, or OpenSSL dependencies. Emits register-allocated native loops, CPUID AVX2/SSE2/AES-NI bulk operations, 12-bucket ORO slab recycling, OS-native readiness reactors (epoll/kqueue/IOCP), full DNS/TCP/UDP/TLS 1.3 networking (net/dns, net/client, web), and opt-in .ffi C-ABI shared library interop.

Part IV: How-To Guide & Newcomer Mental Model

Step-by-step pointers for reading and writing idiomatic .vk code, inspecting parsed programs, building Veko workspaces, and regenerating documentation.


0. Pointers & Best Practices for Newcomers (How to Read & Write Veko)

1. Shift Your Mental Model from "Punctuation" to "CLI Commands"

Newcomers arriving from Go, Rust, or TypeScript often try to read Veko like C without parentheses and get tripped up. Instead, read each Veko line like a Unix shell command with fixed compile-time arity:

VEKO
os/write-file out_path payload
  • Reading tip: Every word consumes a known number of arguments to its right. Zero-argument functions (such as host-bin-path in build.vk) run simply by naming them — no () needed.
  • Parentheses rule of thumb: Never attach ( directly to a function name (len(xs) is wrong). Use (...) only when an argument is itself a multi-token expression:
VEKO
  while i < (len items) [ ... ]

2. Treat Whitespace as Semantic Punctuation

In C-family languages, spaces are mostly optional decoration. In Veko, spaces separate words while tightness glues paths and accessors together:

  • Space around - and / when doing math: n - 1 and a / b. Without spaces, n-1 is a single kebab-case identifier and str/join is a module path.
  • Keep . and [...] tight to the target: user.name.trim, buf[0..n]. A leading space turns .ok or .tls into an enum literal (return .ok).
  • Space before unary -: add x -1 passes -1; x - 1 subtracts 1.

3. Flatten Nested Parentheses with \ Pipes and . Chains

The primary readability anti-pattern in prefix languages (such as Lisp) is deeply nested parentheses like (f (g (h x))). Idiomatic Veko stays flat in three ways:

  1. Bind intermediate steps with short names when performing side effects.
  2. Use tight . chains for 1-argument transforms: raw.trim.lower.
  3. Use \ pipes for multi-step data transformations (feeding the left result into argument 1 of the next word):
VEKO
   urls = body
       \ json/decode
       \ filter fn [p] [p.active]
       \ map fn [p] [p.url.trim]

4. Read /refinements and /or as Inline Control Flow

Instead of option structs, overloaded functions, or try/catch blocks, Veko extends words with / refinements and handles errors right at the call site with /or:

VEKO
port = str/to-i64/or raw_port [ 443 ]
raw  = os/read-file/or path [ e -> return (err `cannot read {path}: {mold e}`) ]
  • Best practice: Handle or propagate errors immediately with /or (or if err? x [ return x ] in sequential scripts), and pair resource acquisition with defer [ ... ] right below it. Never look for nil or null — unit actions return .ok, wire JSON null is .null, and missing lookups return err.

5. Follow the mut Trail & Visual Casing Conventions

When reading unfamiliar Veko code, scan for the word mut. Because Veko requires mut at both the declaration and every mutating call site (bytes/push mut buf 10), any line without mut is guaranteed not to mutate its arguments in place.

  • Naming convention: Stick to Veko's visual casing and hyphenation split — kebab-case for functions and words (encode-header), snake_case for local variables and struct fields (out_path), and PascalCase for types (Upstream). That lets your eye distinguish callable words from values immediately without () at call sites.

1. Build, Test, and Render Documentation

Run the Test Suite

POWERSHELL
veko run tests/run_tests.vk

This verifies:

  • Whitespace-aware lexical disambiguation (tight vs spaced brackets, dot-chains, enums, unary -, binary -).
  • Two-pass Pratt precedence (hash a == hash b, CRC bitwise indexing, multiline \ pipes).
  • Optional gradual and strict types, struct { ... } and interface { ... } definitions, and static + runtime .secret firewalls.
  • O(1) put, CoW isolation, fixed-width 64-bit VKO bytecode roundtripping, veko inspect modes, HTML documentation synthesis, and 3-track parity.

Build Everything in One Step

POWERSHELL
# Refresh HTML documentation only (dist/docs/)
veko docs

# Or run the pure-Veko build orchestrator (`all`, `test`, `docs`, `build`, `fixed-point`, `check`)
veko run build.vk -- all

Running veko run build.vk -- all executes static checks, runs tests/run_tests.vk, refreshes both HTML documentation suites in dist/docs/, and verifies the two-stage S1 == S2 native self-hosting fixed point (dist/bin/veko).

Render Documentation Only

POWERSHELL
veko docs

2. Inspect Tokens and ASTs While Writing .vk Code

Use veko inspect to see exactly how the whitespace-aware lexer and two-pass Pratt parser interpret your source file:

POWERSHELL
# Inspect raw tokens with line:col and [tight] / [spaced] flags
veko inspect --tokens examples/tour.vk

# Inspect the resolved two-pass AST
veko inspect --ast examples/tour.vk

# Inspect compiled 64-bit VKO bytecode
veko inspect --bytecode examples/hello.vk

# Execute a script or launch the interactive REPL
veko run examples/hello.vk
veko repl

Understanding [tight] vs [spaced] in Token Output

Source Snippet Lexer Output Meaning
buf[0..n] lbracket([) [tight] Postfix index/slice on buf
if ok [break] lbracket([) [spaced] Homoiconic code block argument to if
node.url dot_chain(url) [tight] Field read or 1-arg UFCS call on node
mode = .tls enum_lit(tls) [spaced] Shorthand enum symbol .tls
total = a - b minus(-) [spaced] Binary subtraction
add x -1 int_lit(-1) [spaced] Negative integer literal

3. Write Order-Independent Functions and Aliases

Pass 1 of the Veko parser scans fn, macro, def, and use declarations before Pass 2 builds expression trees. You can call helpers defined lower in the same file without forward declarations:

VEKO
use [h = net/http, j = json]
def fetch-fast = h/fetch/timeout

main = fn [url] [
    format-result (fetch-fast url 5s \ j/decode)
]

format-result = fn [data] [
    data.status
]

4. Avoid Common Syntax Traps

  1. Always put spaces around binary - and /:
    • a - b is subtraction; a-b is a single kebab-case identifier.
    • If you accidentally write n-1 when n is in scope, Veko reports:

unknown word 'n-1' -- add spaces for subtraction: 'n - 1'.

  1. Use { ... } for maps and structs, [ ... ] for blocks and lists:
    • Struct definition: Node = struct { url str, port i64 = 443 }
    • Struct literal: Node { url = 'https://veko-lang.org', port = 8443 }
    • List or code block: [1 2 3] or [print 'ok']
  2. Mark in-place mutations with mut on both sides:
    • Signature: trim-buf = fn [mut buf] [ ... ]
    • Call site: trim-buf mut pkt

5. Configure vvm for WebAssembly 3.0 Execution (--wasm)

When executing veko run --wasm <file.vk>, Veko compiles your program to validated WebAssembly 3.0 and launches vvm automatically (discovering ../vvm/dist/bin/windows/vvm.exe, ../vvm/dist/bin/linux/vvm, dist/bin/vvm, or VVM_BIN when set):

POWERSHELL
# Optional override if your vvm binary lives in a custom path
$env:VVM_BIN = "C:\path\to\vvm.exe"
veko run --wasm --check-slabs examples/hello.vk

You can also invoke vvm run --veko directly against .wasm artifacts emitted by veko compile --wasm.


6. Structure Multi-File Projects & Compile .vko Modules

  1. Create a veko.vk manifest at your project root specifying name, relative root (e.g., 'src'), optional external deps, and optional allow-caps = [.fs .clocks .env .net .exec .ui] (plus default-deny .ffi only when explicitly integrating native shared libraries).
  2. Export types, functions, and macros explicitly using pub Type = struct {...}, pub name = fn|macro [...] [...], or export [sym1 sym2]—mutable module globals (pub mut) are rejected by design.
  3. Import using logical names (use [c = lib/codec, auth]); Veko checks reserved built-in namespaces first, project root second, standard library lib/ third, and declared deps fourth.
  4. Audit before running: Run veko inspect --modules src/main.vk to verify topological order, public exports, and transitive capabilities, or compile ORO VM bytecode modules via veko compile --vko mod.vk -o mod.vko and inspect them with veko inspect --vko mod.vko.

7. Run Concurrent Workers & Guarded Networking

  1. Fan out work across isolated spawn tasks: Pass read-only config/values or transfer payloads via bounded chan/new queues (chan/send, chan/recv, chan/select), and collect results deterministically using task/await.
  2. Respect ORO isolation boundaries: Keep mut buffers local to one task (spawn rejects outer mut captures), and tag sensitive keys with bytes/with-secret so channel/network firewalls block accidental leaks.
  3. Authorize networking explicitly when needed: Networking stays disabled by default on VM/Wasm (allow_network = false); enable only required permissions at runtime (veko run --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk or --allow-hosts=api.example.com), or run cached native binaries via veko run --native.

8. Choose Backends & Cross-Compile veko Across All Five Native Targets

EXECUTION MODES

Choosing Between Veko's Three Execution Tracks

Write idiomatic .vk code once and select the runtime envelope matching development speed, isolation, or native deployment.

Interactive SVG • Click any node (5 components)
SOURCE WORKSPACE veko.vk + src/*.vk RUNTIME & DEPLOYMENT ENVELOPES Identical ORO & .secret semantics --vm (default) --wasm --native .wasm PE / ELF / Mach-O Source Veko Source & Manifest veko check --strict-types Development Track A: ORO Bytecode VM veko run app.vk / veko repl Zero-Trust Track B: Wasm 3.0 Sandbox veko run --wasm --fuel=... Production Track C: Native Machine Code veko compile --native Delivery Shipped Artifacts .exe / ELF64 / Mach-O / .vkp
Components:
Source
Veko Source & Manifest
main.vk types.vk
Component 1 of 5
Architectural Role & Purpose

Single source of truth defining module imports, types, and capability declarations.

Contextual Description & System Interaction

Every Veko program starts from the same clean module graph.

Core Functionality & Mechanics
  • Checked once by veko check and formatted by veko fmt
  • Declares allow-caps = [.fs .clocks .env .net .ui] in veko.vk
  • Zero #ifdef soup across VM, Wasm 3.0, and Native targets
Development
Track A: ORO Bytecode VM
oro_vm.vk
Component 2 of 5
Architectural Role & Purpose

Fastest edit-run-test cycle, interactive REPL, and portable .vko bytecode bundles.

Contextual Description & System Interaction

Use Track A during daily coding, scripting, and interactive debugging.

Core Functionality & Mechanics
  • Instant startup with zero link wait
  • Supports dynamic eval and interactive :stats inspection
  • Default engine for veko doc --test
Zero-Trust
Track B: Wasm 3.0 Sandbox
codegen.vk
Component 3 of 5
Architectural Role & Purpose

Deterministic capability-confined execution for untrusted extensions and CI leak audits.

Contextual Description & System Interaction

Use Track B for multi-tenant plugins, reproducible sandboxes, and slab leak verification.

Core Functionality & Mechanics
  • Enforces --fuel instruction budgets and --mem-pages ceilings
  • --check-slabs proves _oro_live_slabs == 0 on exit
  • Blocks .ffi and confines filesystem roots
Production
Track C: Native Machine Code
native_emit.vk arm64_emit.vk
Component 4 of 5
Architectural Role & Purpose

Standalone zero-GC executables with SIMD acceleration and cross-OS compilation.

Contextual Description & System Interaction

Use Track C for production servers, CLI tools, desktop GUIs, and edge appliances.

Core Functionality & Mechanics
  • veko run --native caches compiled binaries by SHA-256
  • Emits win-x64 PE32+, linux-x64/arm64 static ELF64, macos-arm64 Mach-O
  • Supports --gui console-free windows and opt-in --allow-ffi
Delivery
Shipped Artifacts
pe_emit.vk elf_emit.vk macho_emit.vk
Component 5 of 5
Architectural Role & Purpose

Self-contained binaries and Ed25519/ML-DSA signed VKP1 source bundles.

Contextual Description & System Interaction

Deploy tiny self-contained artifacts anywhere from cloud VMs to ARM64 edge nodes.

Core Functionality & Mechanics
  • Zero external runtime, JVM, or garbage collector required
  • Single-file copy deployment to containers or bare metal
  • Cryptographically verifiable supply chain via veko pkg

When to Choose --vm/.vko, --wasm, or --native

  • Choose --vm or .vko for instant local iteration, veko repl, dynamic eval, and precompiled 64-bit VKO distribution.
  • Choose --wasm when executing untrusted or multi-tenant code under vvm's HostSandbox (fuel caps, --mem-pages, --allow-fs, --allow-hosts, --check-slabs).
  • Choose --native (veko run --native or veko compile --native [--target=<win-x64|win-arm64|linux-x64|linux-arm64|macos-arm64>]) when shipping standalone Windows PE32+ (win-x64 & win-arm64 0xAA64, --gui optional), static Linux ELF64 (x86_64 & arm64), or signed 16 KiB Apple Silicon Mach-O (macos-arm64) binaries with zero C/LLVM toolchain dependencies.

src/main.vk hosts the unified 46-module single-binary veko SDK (with all 93 lib/ modules embedded via src/stdlib_vfs.bin) and compiles projects (including itself) to all targets:

POWERSHELL
# Compile the self-hosted veko toolchain to .vko, .wasm, or any of the 5 native OS/CPU targets
veko compile --vko    src/main.vk -o dist/veko.vko
veko compile --wasm   src/main.vk -o dist/veko.wasm
veko compile --native src/main.vk -o dist/bin/veko_s1.exe
veko compile --native --target=win-arm64   src/main.vk -o dist/bin/veko_win_arm64.exe
veko compile --native --target=linux-x64   src/main.vk -o dist/bin/veko_linux_x64
veko compile --native --target=linux-arm64 src/main.vk -o dist/bin/veko_linux_arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/bin/veko_macos_arm64

9. Predictable Memory, Zero Pauses, Zero Lifetimes: How ORO Works in Plain English

Veko's memory model is called ORO (One Reference Only). In plain English, Veko gives you the clean feel of a high-level language with the predictable memory and speed of systems code — without garbage-collection pauses and without lifetime annotations:

  1. Zero-GC (No Garbage Collector): Unlike Python, Go, Java, or JavaScript, Veko runs no background collector thread that periodically pauses your service to scan memory for unreachable objects.
  2. One Clear Owner ("Passing a Physical Clipboard"): Instead of a "Shared Google Doc" where ten distant functions hold hidden references and silently mutate your map behind your back, every Veko value has one clear owner at a time:
    • Reading is free: Passing a value to a read-only function costs zero copying.
    • In-place updates are explicit (mut): If a function updates your buffer in place, you pass mut on the page (bytes/push mut buf 10), and ownership returns immediately when the call completes.
    • Independent copies use Copy-on-Write: Assigning snapshot = draft shares the underlying slab safely until one variable actually mutates it, and strings up to 14 bytes live inline inside the 16-byte value with zero heap allocation.
  3. Deterministic Cleanup & True Secret Zeroization: Because every value has one owner, Veko knows the exact closing ] where a variable goes out of scope:
VEKO
handle-webhook = fn [payload bytes] str [
    // 1. <= 14-byte strings sit inline on registers/stack — 0 heap allocations
    status = 'verified'

    // 2. Explicit in-place mutation: any line without `mut` CANNOT mutate `buf`
    mut buf = bytes/with-cap 256
    bytes/push-all mut buf payload

    // 3. Single-owner secrets zeroize deterministically at scope exit
    api_key = os/getenv/secret/or 'STRIPE_SECRET' [ bytes/with-secret 0 ]

    status
] // <-- Right here: `buf` is freed immediately, and `api_key` RAM bytes are overwritten with 0x00!
Your Background What Zero-GC ORO Determinism Means in Practice
Python / Node / Ruby Services run in 15–30 MB of RAM instead of 500 MB, never suffer random GC latency spikes, and functions cannot silently mutate your maps or lists.
Go Same single-binary compile-and-ship workflow, with zero GOGC/GOMEMLIMIT tail-latency tuning, zero nil panics, and explicit mut on state changes.
Rust Deterministic RAII drops, single-owner safety, and zero GC — without <'a> lifetime annotations, Rc<RefCell<T>>, or Arc<Mutex<T>>.
Security & FinTech A moving garbage collector never copies passwords or keys across RAM; single ownership lets Veko zeroize secret slabs at the exact closing ].

10. Coming from Python, TypeScript, Go, or Rust: Stack Migration Map

Use veko pkg search <query> and veko pkg info <name> to discover any of the 30 official Ed25519-signed .vkp packages on veko-lang.org:

Familiar Stack in Other Ecosystems Idiomatic Pure-Veko Stack (stdlib + veko pkg add ...)
Python: FastAPI + Pydantic + Celery + Chroma/Polars web + openapi@1.0.0 + jobs_cron@1.0.0 + vec_rag@1.0.0 / dataframe_parquet@1.0.0
TypeScript / Node: Next.js + Prisma + Stripe + Apollo + Playwright + Yjs web_live@1.0.0 + db/sqlite (sqlite_orm_ext@1.0.0) + payments_ledger@1.0.0 + graphql@1.0.0 + browser_cdp@1.0.0 + crdt_sync@1.0.0
Go: net/http + chi + grpc-go + ko + client-go + etcd/raft web (net/http2, net/http3) + http_router@1.2.0 + grpc_proto@1.0.0 + oci_k8s@1.0.0 + cluster_raft@1.0.0
Rust: axum + tower + snow (Noise) + extism + rumqttc web + resilience@1.0.0 + noise_tunnel@1.0.0 + wasm_plugin_sdk@1.0.0 + iot_mqtt@1.0.0
Enterprise / DevOps: boto3 + Ansible/Terraform + Okta SAML/SCIM + WebAuthn cloud_s3@1.0.0 + iac_fleet@1.0.0 + ldap_saml@1.0.0 + webauthn@1.0.0 + ai_mcp@1.0.0 + ai_llm@1.0.0

Part V: Veko — Developer Tooling Guide (debug, --coverage, fuzz, fmt, lsp, VS Code & pkg)

Veko ships its entire developer experience inside the single self-hosted veko executable with zero external runtime dependencies: an interactive CLI source debugger & VS Code F5 Debug Adapter Protocol server (veko debug, veko debug --dap), compiler-verified line coverage (veko test --coverage, --lcov), deterministic structure-aware fuzzing & counterexample shrinking (lib/testing/fuzz.vk), a whitespace-safe formatter (veko fmt), a native Language Server Protocol 3.17 server (veko lsp), self-contained HTML API docs with live Wasm 3.0 <canvas> previews (veko doc --html), Light-Mode SVG flamegraphs (--flamegraph), veko-lang.org + decentralized HTTPS .vkp package management (veko pkg add, ~/.veko_modules, veko.lock), and assisted Go/Python/Rust/V migration translators.

DEVELOPER TOOLING

Self-Hosted Formatter, LSP Server, Doctest Runner & Source Migrators

Every IDE, formatting, documentation, package-signing, and code-migration tool ships inside the single veko binary.

Interactive SVG • Click any node (6 components)
CODE QUALITY & IDE INTELLIGENCE fmt_cmd.vk + lsp_cmd.vk + editors/vscode EXECUTABLE DOCS, PACKAGING & MIGRATION doc_cmd.vk + docgen.vk + migrate_cmd.vk textDocument/formatting Shared frontend Auto-format .vk Verified modules Formatting veko fmt Whitespace-Safe Formatter IDE & LSP veko lsp + VS Code JSON-RPC 2.0 + Visual Inspector Introspection veko inspect & repl --tokens / --ast / --modules / --vko Documentation veko doc --test & docs Verified API Docs + 3-Col HTML Migrators go2vk / py2vk / rs2vk / v2vk Assisted Ecosystem Migration Package Signing veko pkg pack / verify / inspect
Components:
Formatting
veko fmt
fmt_cmd.vk
Component 1 of 6
Architectural Role & Purpose

Enforces canonical tab indentation while preserving Veko's load-bearing [tight]/[spaced] tokens.

Contextual Description & System Interaction

Eliminates style debates without ever altering program semantics.

Core Functionality & Mechanics
  • Idempotent: fmt(fmt(x)) == fmt(x) verified across all modules
  • Preserves // comments, single-quoted strings, andtight slices
  • Supports --write (-w), --check (CI gate), and --diff
IDE & LSP
veko lsp + VS Code
lsp_cmd.vk
Component 2 of 6
Architectural Role & Purpose

Provides real-time diagnostics, hover types/caps, go-to-definition, completions, and quick-fixes.

Contextual Description & System Interaction

Delivers instant language-server feedback from the self-hosted compiler frontend.

Core Functionality & Mechanics
  • Streams live type, arity, mut-loan, and .secret diagnostics on type
  • Suggests Levenshtein 'did you mean' codeAction repairs
  • Pairs with editors/vscode TextMate grammar & Visual Inspector
Introspection
veko inspect & repl
inspect.vk main.vk
Component 3 of 6
Architectural Role & Purpose

Exposes every compiler stage for transparent debugging and interactive exploration.

Contextual Description & System Interaction

Makes the compiler a transparent glass box for both learners and tool authors.

Core Functionality & Mechanics
  • Inspect exact [tight]/[spaced] tokens, Pratt ASTs, and module DAGs
  • Disassemble 64-bit VKO bytecode (--vko) and Wasm sections (--wasm)
  • Interactive REPL (:help, :stats, :reset) for live prototyping
Documentation
veko doc --test & docs
doc_cmd.vk docgen.vk
Component 4 of 6
Architectural Role & Purpose

Extracts module API docs, executes fenced code examples, and builds interactive HTML suites.

Contextual Description & System Interaction

Ensures code examples in library comments and guides never rot.

Core Functionality & Mechanics
  • veko doc --test runs module doctests on --vm, --wasm, or --native
  • Infers required capabilities (.fs, .net, .ui, .ffi) per function
  • veko docs builds dark/light HTML handbooks + SVG diagrams
Migrators
go2vk / py2vk / rs2vk / v2vk
migrate_cmd.vk v2vk_cmd.vk
Component 5 of 6
Architectural Role & Purpose

Translates Go, Python, Rust, and V source files into idiomatic, formatted Veko skeletons.

Contextual Description & System Interaction

Accelerates porting existing utilities and algorithms into safe pure Veko.

Core Functionality & Mechanics
  • Maps foreign imports to pure-Veko stdlib equivalents automatically
  • Rewrites control flow, functions, and structs into prefix .vk syntax
  • Runs veko fmt automatically and annotates manual review spots
Package Signing
veko pkg
lib/pkg/vkp.vk main.vk
Component 6 of 6
Architectural Role & Purpose

Packages, inspects, and cryptographically verifies reproducible VKP1 module bundles.

Contextual Description & System Interaction

Completes the zero-dependency developer workflow from init to signed release.

Core Functionality & Mechanics
  • Merkle SHA-256 tree over canonicalized module paths
  • Ed25519 and post-quantum ML-DSA-65 detached/embedded signatures
  • Pins trusted publisher keys via --trust or veko.vk trust-keys

1. Canonical Source Formatter (veko fmt)

veko fmt enforces consistent tab indentation for [ ... ] and { ... } blocks, continuation \ pipe alignment, LF line endings, trimmed trailing whitespace, and single blank-line separation while strictly preserving Veko's load-bearing [tight] vs [spaced] token boundaries, single-quoted strings, and // comments.

POWERSHELL
# Print formatted output to stdout
veko fmt src/app.vk

# Format a file or entire directory tree in place
veko fmt --write src/

# CI gate: exit non-zero if any .vk file needs formatting
veko fmt --check src/ lib/ examples/

# Preview a unified diff without modifying files
veko fmt --diff src/app.vk

Formatting is guaranteed idempotent: running veko fmt twice produces byte-identical output.


2. Native Language Server (veko lsp)

veko lsp runs a pure-Veko JSON-RPC 2.0 Language Server over standard input/output (Content-Length framing). Any LSP-compatible editor (VS Code, Neovim, Helix, Zed) can launch veko lsp directly with no Node.js or external language server binary.

LSP Feature Method Capabilities
Live Diagnostics textDocument/publishDiagnostics Lexer, parser, gradual/strict types, mut borrow rules, .secret sinks, and veko.vk capability checks on open/change/save
Hover Documentation textDocument/hover Signatures and // doc comments for local symbols, imported stdlib modules (doc_cmd), and core Veko keywords
Go to Definition textDocument/definition Jumps to top-level fn, struct, and constant definitions in the current file or imported modules
Contextual Completion textDocument/completion Triggered on /, ., and \: module exports (dt/), enum literals (.ok, .fs, .exec), local defs, and Veko builtins
Document Outline textDocument/documentSymbol Structured outline of top-level functions, structs, and values
Canonical Formatting textDocument/formatting Formats documents directly via veko fmt
Quick-Fix Code Actions textDocument/codeAction Turns 'did you mean ...' diagnostics into 1-click workspace edits

Connecting Other Editors to veko lsp

Because veko lsp speaks standard JSON-RPC 2.0 over stdio, non-VS Code editors connect with a few lines of configuration:

  • Helix (~/.config/helix/languages.toml):
TOML
  [language-server.veko-lsp]
  command = "veko"
  args = ["lsp"]

  [[language]]
  name = "veko"
  scope = "source.veko"
  file-types = ["vk"]
  comment-token = "//"
  indent = { tab-width = 4, unit = "\t" }
  language-servers = ["veko-lsp"]
  auto-format = true
  • Neovim (init.lua — built-in vim.lsp.start):
LUA
  vim.filetype.add({ extension = { vk = "veko" } })
  vim.api.nvim_create_autocmd("FileType", {
    pattern = "veko",
    callback = function(ev)
      vim.lsp.start({
        name = "veko-lsp",
        cmd = { "veko", "lsp" },
        root_dir = vim.fs.dirname(vim.fs.find({ "veko.vk", ".git" }, { upward = true })[1] or ev.file),
      })
    end,
  })

3. Visual Studio Code Extension (editors/vscode/)

The repository includes a zero-dependency VS Code extension in editors/vscode/ (also packaged as an installable veko-lang-1.0.0.vsix bundle with zero Node build step or external language server installation required).

Veko VS Code Extension — Light-Mode .vk Syntax Highlighting, CodeLens Bar & Live veko check / run Output

3.1 Installing the Extension

Choose one of the following installation methods:

  • Install Packaged .vsix Bundle (Recommended for End Users):
POWERSHELL
  code --install-extension veko-lang-1.0.0.vsix
  • Windows (PowerShell — Copy from Repository):
POWERSHELL
  Copy-Item -Recurse -Force .\editors\vscode "$env:USERPROFILE\.vscode\extensions\veko-lang"
  • Linux / macOS (Symlink — Auto-Tracks Repo Updates):
BASH
  ln -s "$(pwd)/editors/vscode" "$HOME/.vscode/extensions/veko-lang"
  • Try Immediately Without Installing:
POWERSHELL
  code --extensionDevelopmentPath=./editors/vscode .

After copying or symlinking, reload VS Code (Ctrl+Shift+P / Cmd+Shift+P -> Developer: Reload Window).

3.2 Configuring VS Code Settings

Open Settings (Ctrl+,) or edit your User/Workspace settings.json to point the extension at your self-hosted veko binary and enable canonical tab-based format-on-save:

JSON
{
  "veko.executablePath": "dist/bin/veko.exe",
  "veko.strictTypes": false,
  "[veko]": {
    "editor.formatOnSave": true,
    "editor.insertSpaces": false,
    "editor.tabSize": 4
  }
}
  • Set veko.executablePath to "veko" if the binary is already on your PATH, or an absolute path such as "/path/to/veko/dist/bin/veko" on Linux.
  • Set "veko.strictTypes": true if you want Veko: Check Types & Secrets to enforce --strict-types by default.

3.3 Using the Extension (LSP, CodeLens & Command Palette)

Opening any .vk file automatically activates syntax highlighting and starts veko lsp in the background:

  • Editor Intelligence: Hover over functions, structs, or stdlib paths (datetime/parse-rfc3339) for live signatures & docs; press F12 for Go to Definition; trigger completion on /, ., and \; press Shift+Alt+F to format via veko fmt; click the lightbulb (Ctrl+.) to apply 1-click 'did you mean?' quick-fixes.
  • Top-of-File CodeLens Bar: Every .vk file displays one-click links at line 1: Run (VM), Run (Wasm), Check, Docs, Doctest, and Inspect.
  • Visual Inspector Side Panel (Veko: Open Visual Inspector): Opens a theme-aware Webview panel beside your editor with 5 switchable tabs (--tokens, --ast, --modules, --bytecode, --wasm), live token filtering, color-coded [tight] vs [spaced] whitespace badges, click-to-jump from any token row directly to its line:col in the editor, and automatic refresh whenever you save the .vk file.

![Veko Visual Inspector Side Panel — Interactive [tight] vs [spaced] Token Table Alongside .vk Source](../screenshots/vscode_02_visual_inspector_light.png)

  • Command Palette (Ctrl+Shift+P -> type Veko:):
Command CLI Equivalent Purpose
Veko: Run Current File veko run <file> Execute active .vk file on the 64-bit ORO VM
Veko: Debug Current File (F5) veko debug --dap Launch interactive VS Code F5 DAP debugging with breakpoints, call stacks, expandable structs/maps, and <secret> redaction
Veko: Run in Wasm 3.0 Sandbox veko run --wasm <file> Execute active .vk file inside vvm Wasm 3.0
Veko: Check Types & Secrets veko check [--strict-types] <file> Run static gradual/strict types, mut borrow, and .secret checks
Veko: Format Document veko fmt (via LSP) Format active buffer canonically in place
Veko: Show API Docs for Current File veko doc <file> Display extracted // API signatures, capabilities, and examples
Veko: Look Up Module / Symbol Docs veko doc <mod> [sym] Prompt (pre-filled from cursor) to look up any stdlib or workspace symbol
Veko: Export API Docs (api.json) veko doc --json <file> -o <file>.api.json Write machine-readable JSON API docs alongside the file
Veko: Export API Docs (Markdown) veko doc --md <file> -o <file>.api.md Write Markdown API reference alongside the file
Veko: Run Doctests veko doc --test <file> Execute all fenced vk ` doctests in the current file
Veko: Build HTML Documentation & Playground veko docs Regenerate all End-User & Technical HTML handbooks into dist/docs/
Veko: Open Visual Inspector veko inspect --tokens|--ast|--modules|--bytecode|--wasm <file> Open the interactive side-by-side Visual Inspector Webview with live tabs, [tight]/[spaced] badges, click-to-jump tokens, and auto-refresh on save
Veko: Inspect Tokens / AST / Modules / Bytecode / Wasm veko inspect <flag> <file> Open the Visual Inspector directly on the chosen tab

3.4 Troubleshooting

  • No diagnostics or hover appearing: Open View -> Output and select the Veko channel. Verify that veko.executablePath points to a working binary (veko version works in your terminal).
  • Spaces instead of tabs on Enter: Confirm "[veko]": { "editor.insertSpaces": false } is set in settings.json so VS Code matches veko fmt's canonical tab indentation.

4. API Docs, Doctests & Interactive Web Playground (veko doc & veko docs)

4.1 Terminal, Self-Contained HTML & Doctest API Docs (veko doc)

  • Live API Lookup: Run veko doc <module> [symbol] in your terminal (e.g. veko doc datetime parse-rfc3339 or veko doc ui open-window) to inspect signatures, capabilities, and examples directly from source // comments.
  • Self-Contained Light-Mode HTML API Docs: Render any module or workspace into a zero-CDN, single-file HTML reference (veko doc --html -o api_docs.html lib/ui.vk) or multi-page directory (veko doc --html --out-dir=dist/api lib/) complete with live symbol search, Wasm 3.0 executable doctest cells, and interactive <canvas> RGBA32 framebuffer previews:

Veko Self-Contained HTML API Reference — Light-Mode Signatures, Capabilities & Live Wasm 3.0 Canvas Surface

  • Machine-Readable Exports: Emit api.json (veko doc --json <mod> -o api.json) or Markdown (veko doc --md <mod> -o api.md).
  • Multi-Track Doctests: Verify every fenced vk example across VM, Wasm 3.0 (--check-slabs), and Native x86_64 / ARM64 via veko doc --test [--vm|--wasm|--native|--all] <mod>...`.

4.2 Building & Using the Interactive Web Documentation Playground

Every Veko documentation site generated by veko docs includes a built-in, zero-CDN Interactive Code Playground embedded directly on every Veko code block:

  1. Generate the HTML documentation suite:
POWERSHELL
   veko docs

This renders standalone End-User HTML pages into dist/docs/user/index.html (and Technical docs into dist/docs/technical/index.html).

  1. Open in any browser (works offline via file:// or over HTTP):
POWERSHELL
   # Windows
   Start-Process dist\docs\user\index.html

   # Linux / macOS
   xdg-open dist/docs/user/index.html
  1. Use the Code Cell Toolbar: Above every Veko snippet you will see a VEKO header bar with two buttons:
    • Copy — Copies the snippet directly to your clipboard.
    • Playground — Opens an editable code cell right below the snippet with three controls:
      • Inspect Tokens — Runs the built-in browser Veko tokenizer live on your edits and prints every token with its exact [spaced] vs [tight] whitespace tag (enum_lit, path, str_lit, word, delim). This is ideal for learning and debugging Veko's whitespace rules interactively.
      • Run (Wasm / CLI) — If a browser Wasm runner hook (window.VEKO_WASM_RUNNER) is attached on the host page, executes your edited code live in-browser and prints stdout; otherwise displays the exact offline veko check / veko run --wasm / veko fmt --diff commands to run locally.
      • Reset — Restores the cell back to the original documentation example.
  2. Optional Custom Wasm / Local Runner Hook: When hosting dist/docs/user/ behind a web app or Wasm bridge, define a single function before interactive.js runs:
JAVASCRIPT
   window.VEKO_WASM_RUNNER = function(sourceCode) {
     return myVekoRuntime.eval(sourceCode);
   };

All Run (Wasm / CLI) buttons across every documentation page automatically invoke window.VEKO_WASM_RUNNER(sourceCode) and display its output inline.


5. Call-Frame Profiling, Light-Mode SVG Flamegraphs & veko.lock

5.1 Deterministic Call-Frame Profiler (--profile & --flamegraph)

veko run and veko bench include a zero-overhead-when-disabled call-frame profiler (lib/profile/flamegraph.vk) that records exact call counts, self nanoseconds, and inclusive call stacks across qualified Veko functions:

POWERSHELL
# Print top hot functions by self/inclusive time and emit an interactive Light-Mode SVG flamegraph
veko run --flamegraph=dist/profile.svg src/main.vk
veko bench --flamegraph=dist/bench_flame.svg tests/

Veko Interactive Light-Mode SVG Flamegraph — Call-Stack Hierarchy, Self/Inclusive Timing & Click-to-Zoom

5.2 Interactive Source Debugger & VS Code F5 DAP (veko debug)

veko debug provides both an interactive terminal source debugger ((veko-dbg)) and a zero-dependency Debug Adapter Protocol server (veko debug --dap) wired directly into VS Code's F5 debugger (editors/vscode/):

POWERSHELL
# Interactive CLI debugger (pause on entry or at explicit -b breakpoints)
veko debug examples/38_zero_ffi_sqlite_and_orm.vk
veko debug -b 18 --script="bt;locals;n;c" examples/38_zero_ffi_sqlite_and_orm.vk
  • Interactive Commands: s/step (step into), n/next (step over), f/finish (step out), c/continue, b [file:]line, d <id>, bt (stack trace), locals, globals, p <expr> (evaluate local, dotted field, or expression), and l (source window).
  • End-to-End .secret Redaction: Every .secret binding, struct field, or map entry automatically renders as <secret> across CLI locals/print, VS Code Variables panes, and hover tooltips—preventing accidental credential exposure during debugging sessions.

VS Code F5 Source-Level DAP Session — Paused on Breakpoint with Call Stack, Locals & Live <secret> Redaction

Veko Source Debugger & VS Code DAP Inspector — Breakpoints, Call Stack, Expandable Structs & .secret Redaction

5.3 Compiler-Verified Line Coverage & Structure-Aware Fuzzing (veko test --coverage & testing/fuzz)

veko test --coverage records exact VKO source-line hits per module, prints a terminal coverage summary, writes optional LCOV (--lcov=dist/lcov.info) for CI gutters, and renders a self-contained Light-Mode HTML Coverage Report:

POWERSHELL
veko test --coverage=dist/coverage.html --lcov=dist/coverage.info examples/39_debugger_coverage_and_fuzzing.vk

Veko Light-Mode HTML Line Coverage Report — KPI Summary, Per-Module Distribution Bars & Annotated Source Lines

Pair line coverage with lib/testing/fuzz.vk (fuzz-bytes, fuzz-str, fuzz-block) to run deterministic SplitMix64 property campaigns across --vm, --wasm, and --native with automatic delta-debugging counterexample shrinking down to minimal failing byte slices, UTF-8 strings, or nested homoiconic [ ... ] blocks.

5.4 Single-Binary Portable SDK, veko-lang.org Registry & ~/.veko_modules (veko pkg)

All 95 standard library modules are embedded inside the single veko binary (stdlib_vfs.vk across all 5 native SDK targets: win-x64, win-arm64 PE32+ 0xAA64, linux-x64, linux-arm64, and macos-arm64, distributed for Windows as veko-1.0.0-win-x64.zip and veko-1.0.0-win-arm64.zip), while environment variables and ~/.veko_modules keep host configuration clean and predictable:

Path / Variable Purpose
Embedded VFS (stdlib_vfs.bin) Built-in compressed stdlib inside veko so veko run, veko compile, and veko doc work anywhere with zero external directories
VEKO_HOME Optional SDK root override ($VEKO_HOME/lib overrides stdlib modules; $VEKO_HOME/bin locates vvm)
~/.veko_modules (VEKO_MODULES) User-level cache (cache/<sha256>.vkp) and installed package store (pkgs/<name>@<ver>.vkp) shared across workspaces
VEKO_LIB Native shared library search path (; on Windows, : on Linux/macOS) consulted by lib/ffi.vk (ffi/open-lib)
https://veko-lang.org/pkg (VEKO_REGISTRY) Official HTTPS .vkp registry for bare name@ver specs alongside decentralized https://... .vkp URLs
POWERSHELL
# Add an official package from https://veko-lang.org/pkg/<name>/<ver>.vkp or any decentralized HTTPS URL
veko pkg add http_router@1.2.0
veko pkg add https://example.org/veko/custom_codec-0.4.0.vkp

# List cached ~/.veko_modules packages, write veko.lock, or verify in CI
veko pkg list
veko pkg lock
veko pkg fetch
veko pkg verify-lock

6. Assisted Migration Translators (veko go2vk, py2vk, rs2vk, v2vk & migrate)

Veko includes built-in assisted translators for Go, Python, Rust, and V that rewrite core syntax into canonically formatted Veko starter files AND automatically map standard libraries and popular ecosystem packages directly onto Veko's 93-module pure-.vk standard library (use [...]):

POWERSHELL
# Direct language shorthands
veko go2vk path/to/service.go -o src/service.vk
veko py2vk path/to/script.py  -o src/script.vk
veko rs2vk path/to/module.rs  -o src/module.vk
veko v2vk  path/to/legacy_mod -o src/migrated.vk

# Unified command (auto-detects by extension or explicit --from=go|py|rust|v)
veko migrate --from=go path/to/service.go -o src/service.vk

Automatic Standard Library & Dependency Mapping

Domain Go (go2vk) Python (py2vk) Rust (rs2vk) Veko use [...] Target
HTTP Client & Web net/http requests, httpx, flask, fastapi reqwest, axum, actix_web, warp hc = net/client, web
HTML & Templates html/template, text/template html, jinja2 maud, askama html, tpl = template
Date & Time time datetime, time chrono, std::time dt = datetime
Filesystem & Paths os, io/fs, path/filepath os, pathlib, shutil std::fs, std::path fs, path
JSON / TOML / CSV encoding/json, BurntSushi/toml, encoding/csv json, tomllib, csv serde_json, toml, csv builtin json, toml = codec/toml, csv = codec/csv
Crypto & TLS 1.3 crypto/sha256, crypto/aes, crypto/ed25519, crypto/tls hashlib, hmac sha2, sha3, blake2, aes_gcm, ed25519, rustls crypto/{sha256,sha3,blake,aes,x25519}, tls13 = net/tls13
Auth (JWT & TOTP) golang-jwt/jwt, pquerna/otp pyjwt, pyotp jsonwebtoken jwt = auth/jwt, totp = auth/totp
Databases jackc/pgx, lib/pq, go-redis psycopg, redis postgres, tokio_postgres, redis pg = db/postgres, redis = db/redis
Archives & Deflate archive/tar, archive/zip, compress/gzip tarfile, zipfile, gzip, zlib tar, zip, flate2 tar = archive/tar, zip = archive/zip, deflate = compress/deflate
Net, Regex, Logs, CLI net/netip, gorilla/websocket, regexp, log/slog, google/uuid, semver ipaddress, websockets, re, logging, uuid, difflib, tenacity std::net, tungstenite, regex, tracing, uuid, clap, semver ip = net/ip, ws = net/websocket, regex, slog, rnd = rand, diff, retry, cli, sv = semver
  • Honest Boundary Markers: Foreign or incompatible constructs (C. / cgo, unsafe, sync.Mutex, Arc<Mutex>, async fn, try/except, shared, veb, sqlite) are always preserved with explicit // TODO(go2vk|py2vk|rs2vk|v2vk): ... comments so nothing is silently mis-translated.
  • Auto-Formatted Output: Every translator passes its generated .vk code through veko fmt.

7. LLMs & Coding Agents (AGENTS.md, veko init --agents & llms.txt)

Because Veko has a compact prefix grammar, deterministic One Reference Only (ORO) ownership (zero <'a> lifetime loops), <10ms veko check feedback, and offline veko doc <module> introspection across all 95 embedded stdlib modules, LLMs write idiomatic .vk code immediately when AGENTS.md is present in the workspace root.

POWERSHELL
# Every new workspace created with `veko init` automatically includes AGENTS.md:
veko init my-service

# Add AGENTS.md, CLAUDE.md, .claude/settings.json, .cursor/rules/veko.mdc,
# and .github/copilot-instructions.md to any new or existing project:
veko init --agents .

# Or download the latest standalone AGENTS.md directly from veko-lang.org:
curl -fsSL https://veko-lang.org/AGENTS.md -o AGENTS.md
  • Built-In Agent Introspection Loop: AGENTS.md teaches coding agents to call veko doc <module>, veko pkg search, veko inspect --tokens, veko init --sync, veko check --strict-types, veko fmt -w, and veko test instead of guessing signatures.
  • Web & @Docs Indexing (llmstxt.org): Index https://veko-lang.org/llms.txt or https://veko-lang.org/llms-full.txt in Cursor @Docs, Claude Projects, ChatGPT, or Windsurf for full 95-module stdlib and 30-package context.

8. Environment Diagnostics, CI Scaffolding & Authoring .vkp Packages

veko doctor & veko init --ci

Verify your local SDK, embedded 95-module VKFS archive, ~/.veko_modules cache, veko.vk manifest, AGENTS.md, and registry connectivity in one command, or generate ready-to-push GitHub Actions CI + static container files:

POWERSHELL
# Inspect local SDK, workspace, AGENTS.md, and HTTPS package registry health
veko doctor

# Generate .github/workflows/veko.yml + multi-stage static ELF64 Dockerfile
veko init --ci .

Publishing & Hosting Signed .vkp Packages in 3 Commands

Any developer or team can author, Ed25519-sign, and host a decentralized static HTTPS .vkp package registry on S3, Cloudflare R2, GitHub Pages, or Nginx with zero server code:

POWERSHELL
# 1. Scaffold a publish-ready package workspace (src/mod.vk, examples/demo.vk, tests/, README.md, AGENTS.md)
veko init --pkg my_library

# 2. Generate an Ed25519 publisher keypair (prints your public `ed25519:<hex>` trust-key)
veko pkg keygen -o publisher.ed25519.key

# 3. Pack the signed VKP1 bundle & generate static registry catalog.json + trust-keys.json
veko pkg pack my_library/src -o dist/registry/my_library/0.1.0.vkp --key-file=publisher.ed25519.key --name=my_library --version=0.1.0
veko pkg index dist/registry --registry=https://pkgs.example.org

9. Runnable Tooling & Tail-Latency Proof Demos

Run examples/27_tooling_fmt_lsp_and_v2vk.vk and examples/41_oro_latency_and_memory_proof.vk to verify tooling round-trips and p50–p99.9 ORO tail-latency determinism:

POWERSHELL
veko run examples/27_tooling_fmt_lsp_and_v2vk.vk
veko run -C all examples/41_oro_latency_and_memory_proof.vk
veko bench benchmarks/ --save=dist/bench_baseline.json

Part VI: Standard Library & Post-Quantum Cryptography Guide

Veko ships a 95-module pure-.vk standard library under lib/ (embedded directly inside the single veko binary via stdlib_vfs.vk) that runs identically across all three execution tracks—the 64-bit VKO VM (--vm), the vvm WebAssembly 3.0 sandbox (--wasm), and standalone native x86_64 & AArch64 executables (--native). Every pure data, codec, archive, fuzzing, and cryptographic module requires zero host capabilities, while connected modules (io/*, net/*, reactor, web, db/*, durable/*, ui/*, ffi) declare fine-grained capabilities (allow-caps).

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

1. Complete 95-Module Standard Library Map

Category Modules (use [...]) Highlights Dedicated Guide / Demo
Developer Harness, Fuzzing & Profiling fmt, cli, testing, testing/fuzz, datetime, slog, diff, semver, retry, template, profile/flamegraph Templates, IEC sizes, hexdumps, CLI subcommands, test/bench runner, SplitMix64 byte/UTF-8/homoiconic-block fuzzing & shrinking, RFC 3339 timestamps, structured logs, Myers diff, SemVer 2.0, backoff, interactive Light-Mode SVG flamegraphs examples/17_stdlib_cli_fmt_and_collections.vk, examples/39_debugger_coverage_and_fuzzing.vk
Core Math, Text & Collections math, bits, text, text/re, utf8, path, fs, seq, coll, rand Checked/sat math, IEEE-754 transcendentals, CRC-32/Adler-32/varints, Unicode UTF-8, capture-group Thompson NFA text/re, safe path confinement, high-level fs, merge sort, Set/Ring/Heap/Lru/Memo, UUID v4/v7 examples/17_stdlib_cli_fmt_and_collections.vk, examples/36_regex_captures_zstd_and_otel.vk
Buffers, Streams, Regex & Dialects buf, io, io/{fs,net,open}, glob, regex, dialect ByteReader/ByteWriter/StringBuilder, polymorphic io/Stream & SchemeMux, linear-time ** globbing, ReDoS-proof Thompson NFA regex, homoiconic dialect rewriters examples/18_io_streams_regex_and_codecs.vk
Codecs, Compression, PNG & Packages codec/{wire,hex,url,csv,ini,toml,vbin,cbor,http1,http2,http3,der,pem}, compress/{deflate,zstd}, image/png, archive/{tar,zip}, pkg/{vkp,lock} Schema binary framing, Hex/Base64, URLs, CSV, INI, TOML, VBIN, CBOR, HTTP/1.1, HTTP/2 + HPACK + Huffman, HTTP/3 + QPACK, ASN.1 DER, PEM, DEFLATE/zlib/gzip, RFC 8878 Zstandard, lossless RGBA32 PNG, TAR/ZIP, signed VKP1 + veko.lock examples/25_batteries_datetime_fs_archives_and_toml.vk, examples/37_clipboard_x11_flamegraph_and_lock.vk
Classical Crypto & Sealing crypto/{sha256,sha3,blake,aes,chacha20,kdf,seal,sig,x25519,x509} SHA-256/384/512, HKDF, FIPS 202 SHA3/SHAKE, BLAKE2b, AES-128/256-GCM, ChaCha20 & XChaCha20-Poly1305, PBKDF2, Argon2id, pub sealed Sealed + zeroizing unseal, X25519, Ed25519, P-256/P-384, RSA-PSS, X.509 examples/19_modern_crypto_and_sealed_vault.vk
NIST Post-Quantum Crypto crypto/{mlkem,mldsa,slhdsa} FIPS 203 ML-KEM-512/768/1024, FIPS 204 ML-DSA-44/65/87, FIPS 205 SLH-DSA-SHA2/SHAKE examples/20_post_quantum_nist_pqc.vk
Networking, Web, Auth, OTel & Zero-FFI DBs reactor, conc/scope, otel, net/{dns,ip,client,tls13,http2,http3,websocket}, web, html, auth/{jwt,oauth2,totp}, db/{sqlite,kv,query,postgres,redis,sidecar} Readiness reactor (epoll/kqueue/IOCP), structured task scopes, W3C OpenTelemetry, DNS, Hybrid PQC TLS 1.3 + built-in Let's Encrypt P-256/P-384 CAs, HTTP/2 + Rapid Reset guards, WAN QUIC v1 HTTP/3, streaming web + HEAD + HTML5 DSL, JWT/OAuth2/TOTP, Zero-FFI SQLite 3 (VKJRNL01 crash journal, B-tree indexes, INNER/LEFT JOIN, ORM), WAL KV, pooled TLS PgPool & RESP3 RedisPool Net, Web, DB & VKP1, Async & Reactor
Durable State, Studio UI/Wayland/X11/TUI & Opt-In FFI durable, durable/{object,workflow}, tui, ui, ui/{canvas,font,layout,widgets,wayland,x11}, ffi Crash-safe Durable Objects & Workflows with retry backoff, DLQs & worker leases, TrueColor diffing TUI, RGBA32 2D canvas, font, flex/grid layout, 33 Studio widgets (code-editor, command-palette, file-picker, Tab focus rings), Win32 + Linux Wayland/X11 + macOS arm64 Cocoa + Wasm <canvas> + clipboard/Hi-DPI, and opt-in .ffi (VEKO_LIB) Durable Objects & Workflows, TUI, UI & FFI

2. Inspecting & Testing Libraries with veko doc

Because Veko extracts documentation directly from source // comments and AST signatures, documentation never drifts from the code:

POWERSHELL
# View all exported items in a library module
veko doc fmt

# View a single symbol's signature, capability tags, and doctest
veko doc crypto/mlkem keygen-deterministic

# Generate machine-readable api.json or Markdown API docs
veko doc --json fmt cli testing -o dist/api.json
veko doc --md crypto/aes crypto/seal -o dist/crypto_api.md

# Execute ```vk doctests on the 64-bit VKO VM, Wasm 3.0 (--check-slabs), or Native x86_64
veko doc --test --vm fmt cli testing math bits text path seq coll buf io
veko doc --test --native crypto/mlkem crypto/mldsa crypto/slhdsa
veko doc --test --all fmt cli

3. Developer Harness: fmt, cli, and testing

Formatting, Units, Hex Dumps & Tables (fmt)

fmt turns raw numbers, byte buffers, and tabular records into readable output without external dependencies:

VEKO
use [fmt]

msg = fmt/template 'Synced {name} ({sz}) in {dt}' {
    name = 'edge-eu'
    sz   = (fmt/size 2621440)    // '2.50 MiB'
    dt   = (fmt/dur 12500000)    // '12.50 ms'
}
println msg
println (fmt/format 'radix-16={0} padded={1}' [(fmt/int-radix 255 16) (fmt/hex 42 4)])
println (fmt/table ['Node' 'Status'] [['edge-eu' 'READY'] ['edge-us' 'READY']])

Key functions: fmt/format, fmt/template, fmt/int-radix, fmt/hex, fmt/hex-bytes, fmt/size, fmt/dur, fmt/pad-left, fmt/pad-right, fmt/hexdump, fmt/table.

Declarative CLI Parsing (cli)

cli parses --flag=value, --flag value, short flag clusters (-v), repeatable .list flags, subcommands, -- positional arguments, and auto-renders --help text:

VEKO
use [cli]

spec = cli/CliSpec {
    name    = 'node-ctl'
    version = '1.0.0'
    summary = 'Cluster deployment tool'
    flags   = [
        cli/FlagSpec { name = 'port', short = 'p', kind = .i64, default_val = 8443, help = 'Listen port' }
        cli/FlagSpec { name = 'verbose', short = 'v', kind = .bool, default_val = false, help = 'Verbose output' }
    ]
    commands = [
        cli/CmdSpec { name = 'deploy', summary = 'Deploy a bundle', min_args = 1 }
    ]
}

res = cli/parse/or spec os/args [
    println (cli/render-help spec)
    return (err 'invalid arguments')
]
port = cli/flag-i64 res 'port' 8443

Unit Tests & Micro-Benchmarks (testing)

testing provides structured assertion suites (Suite, new, ok, eq, neq, is-err, is-ok, approx, report, finish) and monotonic benchmarking (bench using .clocks):

VEKO
use [t = testing, m = math]

mut s = t/new 'math-checks'
_ = t/eq mut s (m/gcd 48 18) 6 'gcd'
_ = t/approx mut s (m/sqrt 2.0) m/sqrt2 0.000000000001 'sqrt(2)'
_ = t/report s

4. Core Utilities & Collections: math, bits, text, path, seq, coll, rand

  • math: Zero-overhead compile-time folded constants (math/pi, math/tau, math/e, math/ln2, math/sqrt2, math/i64-max, math/i64-min), overflow-safe integer math (add-checked, sub-checked, mul-checked, add-sat, sub-sat, clamp-i64, gcd, lcm, pow-i64, isqrt), 64/32-bit bitops (popcount, clz, ctz, rotl64, rotr64, rotl32, rotr32), and pure IEEE-754 double-precision transcendentals (sqrt, exp, ln, log2, log10, pow, sin, cos, tan, atan, atan2, floor, ceil, round, trunc, isnan?, isinf?).
  • bits: 24-bit (get-u24-be/push-u24-be) and signed 16/32-bit wire helpers layered over hardware LE/BE intrinsics, IEEE-754 f64-to-bits/bits-to-f64, LEB128 push-varint-u64/read-varint-u64 + zigzag-encode/zigzag-decode, checksums (crc32, adler32, fnv1a-64), byte search (index-of, starts-with?, ends-with?, xor-in-place!), and constant-time equality (ct-eq?).
  • text: String search & replacement (starts-with?, ends-with?, index-of, last-index-of, replace, replace-all, repeat, trim-prefix, trim-suffix), lines, words, ASCII predicates (ascii-alpha?, ascii-digit?, ascii-alnum?, ascii-hex?, ascii-space?), slugify, and UTF-8 scalar codepoint helpers (utf8-len, utf8-codepoints, utf8-from-codepoints).
  • path: Cross-platform lexical path operations (normalize, join, join-all, dir, base, ext, stem, with-ext, is-abs?, split-parts) plus security-first path/confine root rel that rejects absolute paths and .. directory traversal attempts.
  • seq: Stable $O(N \log N)$ sort / sort-by (merge sort), binary-search, reverse, unique, chunk, zip, enumerate, flatten, take, drop, fold, any?, all?, find, partition, group-by, count-by, range-seq.
  • coll: Five everyday data structures backed by Veko 1.0's hybrid hashed map and O(1) in-place put:
    • Set (set-new, set-from, set-add, set-remove, set-has?, set-union, set-intersect, set-diff)
    • Ring (fixed-capacity O(1) FIFO circular buffer: ring-new, ring-push, ring-pop, ring-peek)
    • Heap (binary min-heap priority queue: heap-new, heap-push, heap-pop, heap-peek)
    • Lru (bounded LRU cache: lru-new, lru-get, lru-put, lru-has?)
    • Memo (memo-new, memo-call)
  • rand: Deterministic SplitMix64 + xoshiro256++ PRNG (seed, next-u64, range, f64-unit, bytes-fill, shuffle, choose) for reproducible simulations and tests, plus OS/hardware CSPRNG helpers (csprng-bytes, uuid-v4) for cryptographic randomness.

5. Buffers, Streams, Pattern Matchers & Dialects: buf, io, glob, regex, dialect

Cursor Buffers & ORO Streams (buf, io)

buf provides ByteReader (cursor reads for u8, u16/u32/i64 LE & BE, read-bytes, read-str, read-until), ByteWriter, and StringBuilder. io builds ORO-native value-state Streams (mem-stream, read, write, read-all, write-all, copy, close) and an extensible SchemeMux (mux-default with mem://):

VEKO
use [io]

mux = io/mux-default
mut src = io/mux-open mux 'mem://hello-veko-stream'
mut dst = io/mem-stream (bytes/with-cap 0)
_ = io/copy mut src mut dst 16
println (bytes/to-str (io/read-all mut dst))

Linear-Time Globbing, ReDoS-Proof Regex & Dialects (glob, regex, dialect)

  • glob: Linear-time dynamic-programming matching for *, ** (recursive across /), ?, and [a-z]/[!0-9] character classes (glob/match?, glob/filter).
  • regex: Guaranteed $O(N \cdot S)$ Thompson NFA engine—immune to catastrophic backtracking (ReDoS). Supports literals, ., ^, $, *, +, ?, |, (...), [a-z], [^...], \\d, \\w, \\s (regex/compile, is-match?, find, find-all, replace-all).
  • dialect: Structural tree walker (rewrite-tree, collect), $var/* pattern matcher (match-pattern), clause splitter (split-clauses), and rule compiler (apply-rules) for custom homoiconic DSLs.

6. Wire Formats, Structured Codecs & Compression (codec/*, compress/deflate)

All codecs follow Veko 1.0's "No nil" rules (wire null decodes cleanly to .null, and missing keys/truncated frames return recoverable err values):

  • codec/wire: Declarative binary packet packing & unpacking (Field kinds: .u8, .u16_le, .u16_be, .u32_le, .u32_be, .i64_le, .i64_be, .varint, .f64_be, .bytes_u16_be, .str_u16_be, .raw).
  • codec/hex: Lowercase/uppercase RFC 4648 hexadecimal (encode, encode-upper, decode).
  • codec/url: RFC 3986 Url parser/formatter (parse, format, encode-component, decode-component, parse-query, encode-query).
  • codec/csv & codec/ini: RFC 4180 CSV (parse, parse-records, encode) and .ini/.conf (parse, get, encode).
  • codec/vbin & codec/cbor: Canonical deterministic Veko binary (vbin/encode, vbin/decode) and RFC 8949 deterministic CBOR (cbor/encode, cbor/decode) with sorted map keys and .null round-trip.
  • codec/http2: RFC 9113 binary Frame framing (encode-frame, decode-frame, encode-settings, decode-settings) and RFC 7541 HPACK header blocks (hpack-encode, hpack-decode).
  • codec/der, codec/pem, codec/http1: ASN.1 DER TLV encoding/decoding, RFC 4648 Base64 + PEM blocks, and HTTP/1.1 wire framing.
  • compress/deflate: Pure-.vk RFC 1951 DEFLATE (deflate LZ77 + Fixed Huffman with Stored fallback; inflate supporting Stored, Fixed Huffman, and Dynamic Huffman blocks), RFC 1950 zlib-compress/zlib-decompress (with Adler-32 check), and RFC 1952 gzip-compress/gzip-decompress (with CRC-32 & ISIZE checks).

7. Classical Cryptography & Sealed Envelopes (crypto/*)

Every cryptographic primitive is implemented in 100% pure Veko with zero OpenSSL or OS crypto DLL dependencies:

  • Hash & XOF Families:
    • crypto/sha256: sha256, streaming sha256-init/sha256-update/sha256-digest, sha384, sha512, hmac-sha256, hmac-sha384, hmac-sha512, and RFC 5869 hkdf-* key derivation.
    • crypto/sha3: FIPS 202 Keccak-f[1600] (sha3-256, sha3-512, shake128, shake256, and streaming shake128-init/shake256-init/xof-squeeze).
    • crypto/blake: RFC 7693 BLAKE2b (blake2b, blake2b-256, blake2b-512, blake2b-keyed).
  • Authenticated Encryption (AEAD) & Sealed Envelopes:
    • crypto/aes: Constant-time algebraic AES-128 & AES-256 (zero secret-indexed S-box tables) + NIST SP 800-38D gcm-encrypt/gcm-decrypt with automatic round-key zeroization (bytes/zeroize!).
    • crypto/chacha20: RFC 8439 aead-encrypt/aead-decrypt (12-byte nonce) plus hchacha20 and 24-byte-nonce xchacha20-poly1305-encrypt/xchacha20-poly1305-decrypt.
    • crypto/seal: High-level pub sealed Sealed envelope (external code cannot forge or mutate fields) backed by AES-256-GCM + CSPRNG nonces, portable VKSL wire serialization (to-bytes/from-bytes), and RAII seal/with-open that unseals plaintext into a callback and scrubs it via defer [ bytes/zeroize! mut pt ]:
VEKO
use [seal = crypto/seal]

key = random/bytes 32
env = seal/encrypt key (bytes/from-str 'api-secret-payload') (bytes/from-str 'v1')
wire = seal/to-bytes env
restored = seal/from-bytes wire

n = seal/with-open restored key fn [pt] [ len pt ]
println n   // 18 (plaintext buffer is zeroized automatically when callback returns)
  • Password KDFs & Signatures:
    • crypto/kdf: pbkdf2-sha256, memory-hard RFC 9106 argon2id, and constant-time verify-tag.
    • crypto/x25519: RFC 7748 X25519 key agreement and RFC 8032 Ed25519 signing/verification.
    • crypto/sig: RFC 6979 deterministic ecdsa-p256-pubkey/ecdsa-p256-sign/ecdsa-p256-verify, ecdsa-p384-verify, RSA PKCS#1 v1.5 & RSA-PSS verification, and pkcs8-extract-private-key.
    • crypto/x509 & net/tls13: X.509 v3 certificate parsing/chain validation and pure-.vk RFC 8446 TLS 1.3.

8. NIST Post-Quantum Cryptography (crypto/mlkem, crypto/mldsa, crypto/slhdsa)

Veko ships all three finalized NIST Post-Quantum Cryptography standards natively in pure .vk, built directly atop crypto/sha3 and in-place put NTT polynomial arithmetic:

Standard Module Parameter Sets Purpose
FIPS 203 (ML-KEM) crypto/mlkem .mlkem512, .mlkem768, .mlkem1024 Lattice key encapsulation (KEM) with constant-time implicit rejection on tampered ciphertexts
FIPS 204 (ML-DSA) crypto/mldsa .mldsa44, .mldsa65, .mldsa87 Module-lattice digital signatures with full rejection sampling & hint verification
FIPS 205 (SLH-DSA) crypto/slhdsa .shake_128f, .shake_128s Stateless hash-based signatures (WOTS+ + FORS + XMSS hypertree over SHAKE256)
VEKO
use [kem = crypto/mlkem, dsa = crypto/mldsa, slh = crypto/slhdsa]

// 1. Quantum-resistant key exchange (FIPS 203 ML-KEM-768)
kp = kem/keygen .mlkem768
enc = kem/encaps .mlkem768 kp.ek
ss = kem/decaps .mlkem768 kp.dk enc.ciphertext   // matches enc.shared_secret

// 2. Lattice digital signature (FIPS 204 ML-DSA-65)
skp = dsa/keygen .mldsa65
sig = dsa/sign .mldsa65 skp.sk (bytes/from-str 'release manifest')
ok1 = dsa/verify .mldsa65 skp.pk (bytes/from-str 'release manifest') sig

// 3. Stateless hash-based signature (FIPS 205 SLH-DSA-SHAKE-128f)
hkp = slh/keygen .shake_128f
hsig = slh/sign .shake_128f hkp.sk (bytes/from-str 'root trust anchor')
ok2 = slh/verify .shake_128f hkp.pk (bytes/from-str 'root trust anchor') hsig

9. Runnable Library Demos & Baseline Benchmarks

Explore all standard library modules in action:

POWERSHELL
# Core harness, math, collections, & PRNG (`fmt`, `cli`, `testing`, `math`, `text`, `path`, `seq`, `coll`, `rand`)
veko run examples/17_stdlib_cli_fmt_and_collections.vk

# Streams, matchers, codecs, & compression (`buf`, `io`, `glob`, `regex`, `dialect`, `codec/*`, `compress/deflate`)
veko run examples/18_io_streams_regex_and_codecs.vk

# Classical crypto & sealed vault (`sha3`, `blake`, `aes`, `chacha20`, `kdf`, `seal`, `sig`)
veko compile --native examples/19_modern_crypto_and_sealed_vault.vk -o dist/19.exe ; ./dist/19.exe

# NIST Post-Quantum Cryptography (`mlkem`, `mldsa`, `slhdsa`)
veko compile --native examples/20_post_quantum_nist_pqc.vk -o dist/20.exe ; ./dist/20.exe

# Connected I/O streams, DNS, Hybrid PQC TLS 1.3 (`X25519MLKEM768`) & HTTP/2
veko run --allow-net --allow-listen --allow-private-net examples/21_io_streams_dns_and_pqc_tls.vk

# Web micro-framework, HS256/EdDSA/ML-DSA-65 JWT, OAuth2 PKCE & RFC 6455 WebSockets
veko run --allow-net --allow-listen --allow-private-net examples/22_web_server_websocket_and_jwt.vk

# Embedded crash-safe KV store, PostgreSQL SCRAM-SHA-256, Redis RESP3 & Sidecar RPC
veko run --allow-net --allow-listen --allow-private-net examples/23_zero_ffi_databases_kv_pg_redis.vk

# Signed `VKP1` package bundles (Merkle tree + Hybrid Ed25519 & ML-DSA-65)
veko run examples/24_signed_vkp_package_bundles.vk

# Baseline performance benchmarks (`benchmarks/bench_suite.vk`)
veko compile --native benchmarks/bench_suite.vk -o dist/bench.exe ; ./dist/bench.exe

See Networking, Web, Databases & Signed Bundles Guide for dedicated walkthroughs of io/{fs,net,open}, net/{dns,tls13,http2,websocket}, web, auth/{jwt,oauth2}, db/{kv,postgres,redis,sidecar}, and pkg/vkp.


Part VII: Veko — Networking, Web, Databases & Signed Bundles Guide

This guide explains how to build connected applications, web services, authentication flows, zero-FFI databases, and cryptographically signed 'VKP1' package bundles in pure Veko across all three execution tracks (--vm / .vko, sandboxed --wasm via vvm, and standalone --native binaries across win-x64, win-arm64, linux-x64, linux-arm64, and macos-arm64).

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

1. OS Platform Layer (os/*, time/unix, net/*) & .exec Capability

Veko provides a uniform, deterministic Platform Abstraction Layer (PAL) across Windows, Linux, macOS Apple Silicon, the ORO VM, and the vvm Wasm 3.0 sandbox:

Wall-Clock Time & Positioned File I/O

Builtin Arity Capability Purpose
time/unix 0 .clocks Current UTC wall-clock Unix epoch timestamp in nanoseconds (i64)
os/stdin / os/stderr 1 / 1 .fs Read up to N bytes from standard input / write text to standard error
os/exit 1 — Terminate the current process with integer exit code code
os/cwd / os/temp-dir 0 / 0 .fs Query current working directory or host temporary directory
os/stat / os/read-dir 1 / 1 .fs Inspect file metadata ({ size, is_dir, mtime_ns }, returns err if missing) or list directory entries
os/remove / os/rename 1 / 2 .fs Delete a file/empty dir or atomically rename src to dst
os/open / os/close 2 / 1 .fs Open a file handle ('r', 'w', 'rw', 'a') and close it cleanly
os/pread / os/pwrite 3 / 3 .fs Positioned random-access read (fd off len) and write (fd off bytes)
os/fsync / os/truncate 1 / 2 .fs Flush dirty buffers to stable storage / truncate file to exact byte length

Networking Primitives (net/*)

Builtin Arity Capability Purpose
net/connect-tcp/timeout 3 .net Non-blocking TCP connect enforcing a duration deadline (host port 2s)
net/set-timeout 2 .net Apply per-socket read/write I/O timeout duration (sock 5s)
net/udp-bind 2 .net Bind a UDP datagram socket (net/udp-bind '127.0.0.1' 0)
net/udp-send-to 4 .net Send a UDP datagram (sock host port payload_bytes)
net/udp-recv-from 2 .net Receive a UDP datagram ({ data, host, port }; also supports /timeout)
net/poll 2 .net Poll a block of socket handles for readability with a duration timeout
net/resolve 1 .net Resolve a hostname to a block of IP address strings

Least-Privilege .exec Capability Gate

Subprocess execution (os/exec) is gated by its own dedicated .exec capability rather than .fs. Projects that only read/write files or open sockets cannot spawn external processes unless veko.vk explicitly grants .exec:

VEKO
{
    name       = 'my-service'
    root       = 'src'
    allow-caps = [.fs .clocks .net]   // os/exec is statically denied at check/compile time
}

2. Connected Streams (io/fs, io/net, io/open) & UUID v7

Every transport in Veko adapts cleanly to the io/Stream interface so higher-level protocols (net/http2, net/websocket, web, db/postgres, db/redis) work identically over memory buffers, files, TCP sockets, or post-quantum TLS 1.3 streams.

VEKO
use [io, ifs = io/fs, inet = io/net, iopen = io/open, rnd = rand]

// RFC 9562 time-ordered UUID v7 (monotonically sortable by UTC millisecond timestamp)
req_id = rnd/uuid-v7

// Positioned file stream with explicit fsync
mut wf = ifs/open-write 'data/out.bin'
_ = io/write-all mut wf (bytes/from-str 'hello veko')
_ = ifs/sync wf
_ = io/close mut wf

// Unified URI dispatch (`mem://`, `file://`, `tcp://`, `tls://`, `http://`, `https://`)
mut st = iopen/open 'file://data/out.bin'
payload = io/read-all mut st
_ = io/close mut st

3. DNS, Hybrid Post-Quantum TLS 1.3, HTTP/2, WAN QUIC HTTP/3 & WebSockets

All networking protocols are implemented in 100% pure Veko with zero external crypto or TLS DLLs:

  • net/dns: RFC 1035 wire query encoder (encode-query), response decoder (decode-response), /etc/hosts & /etc/resolv.conf parsers (parse-hosts, parse-resolv-conf), UDP resolver (query-udp), and host lookup (resolve-host). io/net/resolve-ipv4 resolves hostnames using .net only (zero .fs capability required).
  • net/tls13 & crypto/x509 (Hybrid Post-Quantum X25519MLKEM768 + 8 Built-In Public CAs + Custom Roots + Deadlines):
    • Enable hybrid post-quantum key agreement (0x11EC = X25519 + FIPS 203 ML-KEM-768) by passing pqc = true in tls13/connect options, with full TLS 1.3 cipher suite negotiation across AES-128-GCM-SHA256 (0x1301), AES-256-GCM-SHA384 (0x1302), and ChaCha20-Poly1305-SHA256 (0x1303).
    • Validates X.509 chains out of the box against 8 built-in public CA roots (ISRG Root X1, ISRG Root X2, ISRG Root YE, DigiCert Global Root G2, GTS Root R1, Amazon Root CA 1, USERTrust RSA Certification Authority, and USERTrust ECC Certification Authority) plus optional custom enterprise trust anchors (ca_file, ca_pem, or extra_roots_pem) across Ed25519 (0x0807), ECDSA P-256 (SHA-256, 0x0403), ECDSA P-384 (SHA-384, 0x0503), RSA PKCS#1 (SHA-256/384/512), and RSA-PSS (SHA-256 0x0804, SHA-384 0x0805, SHA-512 0x0806), with automatic mtime-based CertReloader hot-reloading and 5s server handshake wall-clock deadlines.
  • net/http2: RFC 9113 HTTP/2 connection layer over io/Stream (client-open, server-accept, request, serve-conn-opts), flow-controlled io/Stream DATA response streaming, and H2ServerOpts DoS protections (max_concurrent_streams, CONTINUATION & HPACK dynamic table caps, and CVE-2023-44487 RST_STREAM Rapid Reset GOAWAY(ENHANCE_YOUR_CALM) enforcement).
  • net/http3: Pure-Veko RFC 9000/9001/9002/9114 QUIC v1 + HTTP/3 UDP client and server (request, serve-h3) featuring contiguous interval-merging ReassemblyBuf stream/CRYPTO reassembly (for multi-packet PQC Initial ClientHellos and out-of-order WAN datagrams), RFC 9000 Appendix A.3 packet number reconstruction (reconstruct-pn), multi-range encode-ack-ranges, 25ms PTO retransmission with cwnd pacing, and post-ClientFinished HANDSHAKE_DONE.
  • net/websocket: RFC 6455 WebSocket upgrade handshake (client-handshake, server-handshake, pure-Veko SHA-1 accept-key) and masked/unmasked framing (write-frame, read-frame).
VEKO
use [tls13 = net/tls13, h2 = net/http2, h3 = net/http3]

// 1. Multiplexed HTTP/2 over hybrid X25519MLKEM768 TLS 1.3 (built-in public CA roots)
mut cconn = tls13/connect 'veko-lang.org' 443 {
    alpn = 'h2'
    pqc  = true
}
mut tst = tls13/tls-stream cconn
mut h2c = h2/client-open mut tst
resp = h2/request mut h2c 'GET' '/api/v1/health' 'veko-lang.org' {} (bytes/with-cap 0)
_ = tls13/close mut cconn

// 2. Native QUIC v1 HTTP/3 over WAN UDP :443
h3_resp = h3/request 'veko-lang.org' 443 'GET' '/api/v1/health' {} (bytes/with-cap 0)

4. Web Micro-Framework (web) & Authentication (auth/jwt, auth/oauth2)

Web Micro-Framework (lib/web.vk), Streaming Bodies & Multi-Worker HTTPS

web provides a composable HTTP/1.1, HTTP/2, and HTTP/3 router with :param and *wildcard segments, automatic RFC-compliant HEAD dispatch on GET and static routes (preserving Content-Length with zero body bytes), middleware chains, built-in security headers (use-security-headers), 413 Payload Too Large header/body guards (max_header_bytes, max_body_bytes), multipart/form-data parsing, traversal-safe static file & 206 Partial Content Range serving (mount-static, serve-static-range), and streaming responses:

  • Streaming Responses (io/Stream & Positioned Files): Use web/stream-response (fixed Content-Length), web/chunked-response + web/encode-chunk (Transfer-Encoding: chunked), or web/stream-file / web/stream-file-range. Static files and byte ranges larger than 256 KiB automatically stream in 64 KiB positioned os/pread chunks across HTTP/1.1 and flow-controlled HTTP/2 DATA frames with constant memory footprint.
  • Non-Blocking Reactor & Multi-Worker HTTPS: web/serve-reactor multiplexes persistent HTTP/1.1 keep-alive connections (max_connections, max_reqs_per_conn) on a single OS readiness poller (epoll/kqueue/IOCP), while web/serve-https and web/https-accept-loop + web/https-worker-loop scale TLS 1.3 + HTTP/2 + HTTP/1.1 across bounded shared-nothing spawn worker pools.

For building full web applications in 100% pure Veko, lib/html.vk provides both a homoiconic Hiccup-style block DSL ([.div { class = 'card' } [ [.h2 ['Title']] ]]) and a typed component builder (html/Node, html/el, html/div, html/document) that compose seamlessly together with automatic XSS escaping, HTML5 void-tag handling, and javascript:/vbscript: URL sanitization. Pair directly with web/view and web/page:

VEKO
use [html, web]

service-card = fn [name str, tags block] html/Node [
    html/article { class = 'card' } [
        (html/h2 {} [(html/text name)])
        [.ul (map tags fn [t] [ [.li [t]] ])]
    ]
]

mut app = web/new-app
web/use-security-headers mut app
web/mount-static mut app '/assets' 'public'

web/get mut app '/dashboard' fn [req web/Request] web/Response [
    viewer = web/query-get req 'user' 'guest'
    web/page 200 'Veko Dashboard' [] [
        [.header [ [.h1 ['Control Plane']] [.p ['Signed in as: ' viewer]] ]]
        [.main [ (service-card 'edge-proxy' ['tls13-pqc' 'http2' 'http3']) ]]
    ]
]

web/get mut app '/releases/:archive' fn [req web/Request] web/Response [
    // Streams >256 KiB archives & 206 Range requests in 64 KiB positioned chunks
    web/serve-static-range 'downloads' (web/param req 'archive' '') (web/header req 'Range' '')
]

When you prefer string-based templates (e.g., emails or config generation), lib/template.vk renders {{ var }} (auto-escaped in render-html, unescaped via {{{ raw }}}), {{#if cond}}...{{else}}...{{/if}}, and {{#each list}}...{{/each}}.

Unified Pure-Veko HTTP/HTTPS Client (lib/net/client.vk)

net/client provides a single ergonomic HTTP/1.1 + HTTPS (TLS 1.3 / PQC + built-in public CA roots) client working identically across --vm, --wasm, and --native with get, head (zero-body HEAD handling alongside 204/304), post-json, request-batch, get-many, keep-alive ConnPool, automatic redirect following (301/302/303/307/308), timeouts, and transparent gzip/deflate response decompression:

VEKO
use [hc = net/client]

head_r = hc/head 'https://veko-lang.org/' (hc/RequestOpts { timeout = 5s })
resp   = hc/get 'https://veko-lang.org/api/v1/health' (hc/RequestOpts { timeout = 5s, pqc = true })
data   = hc/json-body resp

JWT (auth/jwt), OAuth 2.0 PKCE (auth/oauth2) & TOTP 2FA (auth/totp)

  • auth/jwt: Signs and verifies compact RFC 7519/7515 JWTs using HS256 (sign-hs256 / verify-hs256), EdDSA Ed25519 (sign-eddsa / verify-eddsa), and post-quantum ML-DSA-65 (sign-mldsa65 / verify-mldsa65). Validates exp, nbf, iss, and aud against live UTC time/unix via validate-claims, and extracts Bearer headers with parse-bearer.
  • auth/oauth2: Generates RFC 7636 PKCE S256 verifier/challenge pairs (generate-pkce, verify-pkce), CSRF state tokens (generate-state), authorization URLs (authorize-url), and form-encoded token exchange / refresh payloads (token-exchange-body, refresh-token-body).
  • auth/totp: RFC 4648 Base32 (b32-encode, b32-decode), RFC 4226 hotp, RFC 6238 totp-at / totp-now / verify-now (constant-time comparison with skew window), and otpauth-uri provisioning links.
VEKO
use [jwt = auth/jwt, dsa = crypto/mldsa, oa = auth/oauth2]

// Post-quantum ML-DSA-65 JWT with live expiration check
kp = dsa/keygen .mldsa65
now_s = (time/unix) / 1000000000
tok = jwt/sign-mldsa65 kp.sk { sub = 'alice', iss = 'veko.local', exp = now_s + 3600 }
ver = jwt/verify-mldsa65 tok kp.pk
_ = jwt/validate-claims ver.claims (jwt/ClaimOpts { issuer = 'veko.local' })

// OAuth 2.0 PKCE S256
pkce = oa/generate-pkce

5. Zero-FFI Database Stack (db/sqlite, db/kv, db/postgres, db/redis, db/sidecar)

Veko talks to embedded and networked databases—including genuine SQLite 3 files—with zero native C client libraries or FFI:

Zero-FFI SQLite 3 B-Tree Engine, Crash-Safe Journal, Indexes & JOINs (db/sqlite)

lib/db/sqlite.vk implements a 100% pure-Veko reader and writer for standard "SQLite format 3\0" 4096-byte slotted B-tree .sqlite / .db files across --vm, --wasm (.fs only — zero .ffi and zero .clocks!), and --native:

  • Crash-Safe 'VKJRNL01' Hot Rollback Journal & Incremental Page Commits: sq/save and COMMIT write pre-images of dirty 4096-byte pages to <db>-journal with CRC-32 verification (os/fsync), patch only modified pages via positioned os/pwrite + os/fsync, and unlink the journal under <db>-lock advisory coordination. If a power loss or crash interrupts a commit, sq/open (sq/recover-journal) automatically verifies and replays <db>-journal before opening.
  • Multi-Page 0x02/0x0a B-Tree Indexes & $O(\log N)$ Seeks: Writes genuine multi-level interior (0x02) and leaf (0x0a) index B-trees (plus overflow page chains for large payloads) and executes $O(\log N + K)$ binary-search equality and range scans (=, >, >=, <, <=, BETWEEN) via sq/seek-index-btree and sq/seek-table-rowid.
  • Relational INNER JOIN & LEFT JOIN (SQL & Homoiconic sq/q): Supports multi-table aliases, qualified u.col projections/predicates/aggregates, INNER JOIN, and null-extending LEFT JOIN in both sq/query-sql and sq/q:
VEKO
use [sq = db/sqlite]

users = sq/define-table 'users' (quote [
    id     i64 .pk
    email  str .unique
    region str .index
    score  i64 = 0
])

orders = sq/define-table 'orders' (quote [
    id      i64 .pk
    user_id i64 .index
    cents   i64 = 0
])

mut db = sq/open 'data/app.sqlite'
_ = sq/migrate mut db users
_ = sq/migrate mut db orders
uid = sq/insert mut db users { email = 'ada@veko-lang.org', region = 'ca-central-1', score = 98 }
_ = sq/insert mut db orders { user_id = uid, cents = 4900 }

// Homoiconic LEFT JOIN query with qualified projections
rows = sq/q db (quote [
    select [u.email o.cents]
    from users u
    left-join orders o on [u.id == o.user_id]
    where [u.score >= 90]
    order-by [u.score .desc]
    limit 10
])
_ = sq/close mut db

Files written by db/sqlite (sq/open, sq/save, sq/to-bytes) are genuine SQLite 3 binary databases directly readable by the standard sqlite3 CLI and DB Browser for SQLite, while enforcing Veko's .secret firewall on every SQL query and parameter.

Embedded Crash-Safe Transactional KV Store (db/kv)

Built directly on positioned os/{open,pread,pwrite,fsync,truncate,rename,close} with a CRC-32-verified WAL, automatic tail truncation on crash recovery, atomic batches, log compaction, sorted prefix scans, codec/vbin typed storage, and optional AES-256-GCM at-rest encryption (crypto/seal):

VEKO
use [kv = db/kv]

mut store = kv/open 'data/app.vkkv'
_ = kv/put-val mut store 'node:1' { host = 'eu-west-1', active = true }
_ = kv/put-sealed mut store 'vault/token' enc_key32 (bytes/from-str 'secret-value')
_ = kv/compact mut store
keys = kv/scan-prefix store 'node:'
_ = kv/close mut store

PostgreSQL v3.0 TLS, Prepared Extended Queries & Connection Pool (db/postgres)

Pure-Veko PostgreSQL v3.0 protocol client and bounded connection pool (PgConfig, PgPool) supporting PostgreSQL SSLRequest ('S') upgrade to net/tls13, RFC 5802/7677 SCRAM-SHA-256, MD5, and CleartextPassword authentication, binary Extended Query $1, $2... Parse/Bind/Describe/Execute/Sync (query-params, exec-params, named prepare/query-prepared statement caching), savepoint-aware with-tx, and closure-free channel-backed PgPool (new-pool, acquire, release, with-conn with SELECT 1 health checks and auto-reconnect):

VEKO
use [pg = db/postgres]

cfg = pg/PgConfig {
    host     = 'db.internal'
    port     = 5432
    user     = 'veko'
    password = (os/getenv/or 'PG_PASS' [''])
    database = 'appdb'
    tls_mode = .require
}

pool = pg/new-pool cfg 8
rows = pg/with-conn 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, email FROM users WHERE region = $1 AND active = $2' ['ca-central-1' true]
    ]
]
_ = pg/close-pool pool

Redis RESP3 TLS Client, Transactions & Pool (db/redis) & Sidecar RPC (db/sidecar)

  • db/redis: Full RESP3/RESP2 encoder/decoder (supporting strings, blobs, integers, booleans, doubles, big numbers, verbatim strings, maps, sets, attributes, and push frames), RedisConfig (connect with optional TLS 1.3 + ACL AUTH user pass + HELLO 3 negotiation), MULTI/EXEC/DISCARD with-tx transactions, pipelines, and channel-backed RedisPool (new-pool, with-conn with PING liveness validation and auto-reconnect).
  • db/sidecar: CRC-32-verified 'VKSC' binary codec/vbin RPC framing (encode-req, decode-req, encode-resp, decode-resp, call-exec) for integrating external database engines cleanly via .exec-gated subprocesses without in-process FFI.

6. Signed 'VKP1' Package Bundles (pkg/vkp, veko pkg, & trust-keys)

Veko packages multi-module libraries into single-file 'VKP1' binary archives secured by:

  1. Canonical path confinement (rejecting .., leading /, \, and NUL bytes) and strict lexicographical entry sorting,
  2. Per-module SHA-256 digests combined into a deterministic binary SHA-256 Merkle root,
  3. Cryptographic signatures using Ed25519, post-quantum ML-DSA-65, or hybrid dual signatures (both Ed25519 and ML-DSA-65 in the same bundle).

CLI Packaging & Verification (veko pkg)

POWERSHELL
# Pack a directory of .vk modules into a signed VKP1 bundle
veko pkg pack vendor/stats --name=veko-stats --version=1.0.0 --ed25519-seed=<64-hex> -o vendor/stats.vkp

# Inspect manifest, Merkle root, entries, and signer public keys
veko pkg inspect vendor/stats.vkp

# Verify against an explicit trust anchor
veko pkg verify --trust=ed25519:<64-hex-pubkey> vendor/stats.vkp

Installing from veko-lang.org or Decentralized HTTPS (veko pkg add & ~/.veko_modules)

Bare 'name@version' specs resolve from the official https://veko-lang.org/pkg/<name>/<version>.vkp registry (overrideable via VEKO_REGISTRY), while 'https://...' URLs fetch decentralized third-party bundles over pure-Veko TLS 1.3 into ~/.veko_modules and pin their SHA-256 + Merkle root in veko.lock:

POWERSHELL
veko pkg search rag
veko pkg info vec_rag
veko pkg add cloud_s3@1.0.0
veko pkg add openapi@1.0.0
veko pkg add ai_mcp@1.0.0
veko pkg add https://packages.example.org/veko/metrics-0.3.0.vkp
veko pkg verify-lock

Official veko-lang.org Ecosystem Packages (30 Signed .vkp Libraries)

Alongside the 95 embedded VKFS standard library modules, https://veko-lang.org/packages publishes 30 Ed25519-signed pure-Veko .vkp libraries across six production tiers, each bundling full API documentation (README.md), a self-contained runnable example (examples/demo.vk), and 1-click browser WebAssembly 3.0 Playground execution:

Tier Package (veko pkg add ...) Exported Modules Summary
Tier 1 cloud_s3@1.0.0 cloud_s3 AWS Signature V4 signing, presigned GET/PUT URLs, and S3 / R2 / MinIO object client.
Tier 1 data_formats@1.0.0 data_formats, data_formats/yaml, data_formats/xml YAML 1.2 subset codec, XML/XHTML DOM & query helpers, RSS 2.0, and Atom 1.0 feeds.
Tier 1 openapi@1.0.0 openapi, openapi/schema Homoiconic [ ... ] data validator, JSON Schema Draft 2020-12, OpenAPI 3.1, and HTML API Explorer.
Tier 1 smtp_mail@1.0.0 smtp_mail Multipart MIME composer, Ed25519 DKIM signer/verifier, SMTP STARTTLS/TLS client, and Resend/Postmark JSON.
Tier 1 webauthn@1.0.0 webauthn, webauthn/policy FIDO2 / WebAuthn Passkey verifier (CBOR COSE P-256 & Ed25519) + homoiconic RBAC/ABAC policy engine.
Tier 2 grpc_proto@1.0.0 grpc_proto, grpc_proto/proto Protocol Buffers v3 wire codec (varint, zigzag, fixed32/64), homoiconic schema, and 5-byte gRPC framing.
Tier 2 cluster_raft@1.0.0 cluster_raft, cluster_raft/swim Deterministic Raft leader election, replicated log & quorum commit + SWIM gossip failure detector.
Tier 2 mq_streams@1.0.0 mq_streams, mq_streams/nats, mq_streams/kafka NATS Core/Headers wire protocol & wildcard subjects + Kafka RecordBatch v2 (CRC32C) & Produce/Fetch codecs.
Tier 2 db_drivers@1.0.0 db_drivers, db_drivers/mysql, db_drivers/clickhouse MySQL v10 binary handshake, native & caching_sha2 auth, and ResultSet decoder + ClickHouse Zstd JSONEachRow.
Tier 2 resilience@1.0.0 resilience Bounded ORO LRU+TTL cache, GCRA rate limiter, 3-state circuit breaker, backoff, and channel singleflight.
Tier 3 ai_mcp@1.0.0 ai_mcp JSON-RPC 2.0 Model Context Protocol (2025-03-26) server & client with homoiconic tool schemas, stdio, and HTTP.
Tier 3 ai_llm@1.0.0 ai_llm Unified multi-provider chat, tool-calling, structured output, and SSE delta parser (Gemini, Anthropic, OpenAI, Ollama).
Tier 3 vec_rag@1.0.0 vec_rag, vec_rag/bm25, vec_rag/chunker Embedded HNSW vector index + int8 quantization, stemmed BM25 full-text search, RRF hybrid RAG, and SQLite persistence.
Tier 3 dataframe_parquet@1.0.0 dataframe_parquet, dataframe_parquet/arrow Typed columnar DataFrames, homoiconic filter/join/group-agg pipelines, Arrow IPC, and Zstd columnar zone-map codec.
Tier 4 payments_ledger@1.0.0 payments_ledger, payments_ledger/stripe Minor-unit Money math, penny-exact allocation, transactional SQLite double-entry ledger, and .secret Stripe/LemonSqueezy SDK.
Tier 4 graphql@1.0.0 graphql, graphql/parser Zero-codegen homoiconic GraphQL schema, query/fragment parser, batching Dataloader, and HTML5 GraphiQL Explorer.
Tier 4 browser_cdp@1.0.0 browser_cdp Chrome DevTools Protocol (CDP) JSON-RPC session multiplexing, DOM/Page/Network automation, and net/websocket E2E runner.
Tier 4 ldap_saml@1.0.0 ldap_saml, ldap_saml/scim Enterprise SAML 2.0 SP AuthnRequest & signed Assertion verifier, OIDC JWKS matcher, and SCIM 2.0 /Users & /Groups sync.
Tier 5 oci_k8s@1.0.0 oci_k8s, oci_k8s/k8s Daemonless ko-style distroless OCI image builder & registry v2 pusher plus typed Kubernetes manifests & WATCH client.
Tier 5 noise_tunnel@1.0.0 noise_tunnel, noise_tunnel/socks5 Noise Protocol (NN & IKpsk2 X25519+ChaChaPoly) encrypted multiplexed tunnels and RFC 1928/1929 SOCKS5 proxy codec.
Tier 5 iac_fleet@1.0.0 iac_fleet Homoiconic quote [...] Infrastructure-as-Code resource DAG, topological plan diffing, and .secret-redacted provisioning.
Tier 5 wasm_plugin_sdk@1.0.0 wasm_plugin_sdk Multi-tenant Wasm 3.0 host-guest plugin ABI (VKPW), fuel/memory caps, host-call allowlists, and audit trail.
Tier 6 crdt_sync@1.0.0 crdt_sync Hybrid Logical Clocks (HLC), PNCounter, LWW-Map, OR-Set, RGA collaborative text CRDT, and room presence sync.
Tier 6 iot_mqtt@1.0.0 iot_mqtt, iot_mqtt/modbus, iot_mqtt/mdns MQTT 3.1.1/5.0 wire codec & embeddable broker, industrial Modbus TCP registers, and mDNS/DNS-SD .local discovery.
Tier 6 web_live@1.0.0 web_live Homoiconic HTML virtual-DOM differ, keyed patch ops, SSE morphing frames, and typed HTMX helpers.
Tier 6 jobs_cron@1.0.0 jobs_cron, jobs_cron/cron 5-field cron parser & next-tick calculator + crash-safe Zero-FFI db/sqlite persistent job queue.
Tier 6 doc_media@1.0.0 doc_media, doc_media/markdown, doc_media/pdf, doc_media/img, doc_media/ssh GFM Markdown-to-HTML, zero-dep PDF 1.4 generator, RGBA32 image transforms, and OpenSSH Ed25519 & SSHSIG.
Tier 6 http_router@1.2.0 http_router Composable prefix-grouped web/App routers, CORS middleware, sliding-window rate limiters, and request IDs.
Tier 6 veko_ui_kit@1.0.0 veko_ui_kit Accessible Light-First HTML5 KPI cards, data tables, status pills, alerts, breadcrumbs, tabs, and modals.
Tier 6 sqlite_orm_ext@1.0.0 sqlite_orm_ext Base64URL cursor pagination, schema migration versions, audit logs, JSON/CSV export, and DDL diffing.

Consuming Verified .vkp Dependencies in veko.vk

Declare .vkp bundle dependencies alongside trust-keys in veko.vk. The compiler verifies the SHA-256 Merkle root and cryptographic signatures against trust-keys in memory before loading any module AST — unsigned, tampered, or untrusted bundles are rejected automatically:

VEKO
{
    name       = 'my-app'
    root       = 'src'
    allow-caps = [.fs .net]
    trust-keys = [
        'ed25519:a1b2c3...'
        'mldsa65:d4e5f6...'
    ]
    deps = {
        stats = 'vendor/stats.vkp'
    }
}

7. Everyday Batteries (datetime, utf8, fs, slog, archive/*, codec/toml, net/ip, semver, diff, retry)

All everyday utility libraries follow Veko's consistent Subject-Verb-Object (SVO) convention (parse/format, encode/decode, pack/unpack, ? predicates, /or recovery):

Module Capabilities Key APIs
datetime Pure (.clocks for now-utc) DateTime, now-utc, from-unix, to-unix, parse-rfc3339, format-rfc3339, format-http, add-days, with-offset, weekday, leap-year?
utf8 Zero valid?, decode-rune, encode-rune, rune-count, runes, from-runes, multi-byte-safe rune-slice
fs .fs exists?, dir?, file?, mkdir-all, remove-all, walk-dir, glob-dir, copy-file, write-atomic, RAII with-temp-dir
slog .clocks/.fs Logger, new-json, new-kv, with-level, with-fields, format-line, emit, emit-stream, debug/info/warn/error
archive/tar Zero POSIX USTAR TarEntry, pack, unpack, pack-gz, unpack-gz (path-confined + checksum verified)
archive/zip Zero PKZIP ZipEntry, pack, unpack (STORE + DEFLATE via compress/deflate + CRC-32)
codec/toml Zero TOML v1.0 decode & encode ([tables], nested tables, arrays, inline tables, comments)
net/ip Zero IPv4 & IPv6 parse, canonical RFC 5952 format, parse-cidr, contains?, v4?, v6?, loopback?, private?
semver Zero SemVer 2.0.0 parse, format, compare, bump-{major,minor,patch}, satisfies? (^, ~, >=, <, comma AND)
diff Zero LCS line diff diff-lines, equal?, format-unified (--- a / +++ b)
retry .clocks RetryOpts, backoff-delay, run (exponential backoff + jitter), token-bucket RateLimiter (limiter-new, allow?)

8. Runnable Examples & Doctests

Explore and verify every library in this guide across all three execution tracks:

POWERSHELL
# 1. Connected I/O streams, UUID v7, DNS, Hybrid PQC TLS 1.3 (X25519MLKEM768) & HTTP/2
veko run --allow-net --allow-listen --allow-private-net examples/21_io_streams_dns_and_pqc_tls.vk

# 2. Web micro-framework, HS256/EdDSA/ML-DSA-65 JWT, OAuth2 PKCE & RFC 6455 WebSockets
veko run --allow-net --allow-listen --allow-private-net examples/22_web_server_websocket_and_jwt.vk

# 3. Embedded crash-safe KV store, PostgreSQL SCRAM-SHA-256, Redis RESP3 & Sidecar RPC
veko run --allow-net --allow-listen --allow-private-net examples/23_zero_ffi_databases_kv_pg_redis.vk

# 4. Signed VKP1 package bundles (Merkle tree + Hybrid Ed25519 & ML-DSA-65 + tamper rejection)
veko run examples/24_signed_vkp_package_bundles.vk

# 5. Everyday batteries: datetime, utf8, fs, slog, tar.gz/zip, toml, net/ip, semver, totp, diff & retry
veko run examples/25_batteries_datetime_fs_archives_and_toml.vk

# 6. Pure-Veko HTML5 component DSL (`html`), safe templates (`template`), `web/page` & unified `net/client`
veko run --allow-net --allow-listen --allow-private-net examples/26_pure_vk_html_components_and_http_client.vk

# Run all embedded doctests across the networking, web, database, and package libraries
veko doc --test io/fs io/net io/open net/dns net/websocket net/http2 net/client net/ip auth/jwt auth/oauth2 auth/totp web html template db/kv db/redis db/sidecar pkg/vkp datetime utf8 fs slog archive/tar archive/zip codec/toml semver diff retry

Part VIII: Async I/O & Readiness Reactor Guide

Veko delivers high-concurrency, non-blocking network I/O without colored async/await functions, garbage collection, or external C runtimes. Instead of transforming every function into a hidden heap state machine, Veko pairs its single-owner ORO memory model and shared-nothing spawn workers with an OS-native Readiness Reactor (lib/reactor.vk) and non-blocking socket primitives (lib/io/net.vk, lib/web.vk, lib/net/client.vk, lib/net/websocket.vk).


1. Architecture & OS Backends

NON-BLOCKING ASYNC I/O

OS-Native Readiness Reactor, Timer Wheel & Multiplexed HTTP Engine

Single-threaded readiness multiplexing over epoll, kqueue, IOCP+WSAPoll, and WASI net-poll without async/await coloring.

Interactive SVG • Click any node (6 components)
OS KERNEL READINESS POLLERS 11 net/poll-* & net/try-* PAL ops LIB/REACTOR.VK EVENT LOOP Sockets + Min-Heap Timers + Waker HIGH-CONCURRENCY CONSUMERS Server & Batch Client Ready tokens .would_block Next deadline Accept / Read / Write Parallel sockets Kernel PAL OS Kernel Poller Backends epoll / kqueue / IOCP+WSAPoll Zero-Alloc I/O Non-Blocking Socket Ops try-accept / try-read-into / try-write Event Loop Reactor Loop & Dispatch register / modify / step / run Scheduling Min-Heap Timers & Waker after / every + poll-wake Async Server web/serve-reactor Keep-Alive HTTP Multiplexer Async Client net/client/request-batch Parallel Outbound Fan-Out
Components:
Kernel PAL
OS Kernel Poller Backends
native_pal4.vk arm64_pal2.vk
Component 1 of 6
Architectural Role & Purpose

Maps net/poll-new, net/poll-ctl, and net/poll-wait directly to each OS's readiness facility.

Contextual Description & System Interaction

Scales to thousands of idle or slow sockets without thread-per-connection stacks.

Core Functionality & Mechanics
  • Linux x64 & arm64: epoll_create1, epoll_ctl, epoll_pwait
  • macOS arm64: kqueue & EVFILT_READ / EVFILT_WRITE kevent64
  • Windows x64: AFD/WSAPoll readiness + WASI net-poll on Track B
Zero-Alloc I/O
Non-Blocking Socket Ops
lib/io/net.vk
Component 2 of 6
Architectural Role & Purpose

Returns .would_block cleanly instead of blocking the OS thread when buffers aren't ready.

Contextual Description & System Interaction

Preserves ORO single-owner buffer safety across non-blocking state machines.

Core Functionality & Mechanics
  • connect-tcp/nonblock initiates parallel outbound handshakes
  • try-read-into reuses caller-owned mut bytes buffers in place
  • sock-error inspects asynchronous SO_ERROR completion
Event Loop
Reactor Loop & Dispatch
lib/reactor.vk
Component 3 of 6
Architectural Role & Purpose

Multiplexes READABLE and WRITABLE readiness tokens alongside scheduled deadlines.

Contextual Description & System Interaction

Gives systems programmers explicit control over event-driven state machines.

Core Functionality & Mechanics
  • Computes next poll timeout from earliest min-heap timer deadline
  • Dispatches compact ReadyEvent structs without callback hell
  • Zero function coloring: regular Veko functions stay synchronous
Scheduling
Min-Heap Timers & Waker
lib/reactor.vk
Component 4 of 6
Architectural Role & Purpose

Combines O(log n) monotonic timers with cross-thread spawn wakeup notifications.

Contextual Description & System Interaction

Lets hybrid apps combine shared-nothing CPU workers with 1-thread socket multiplexing.

Core Functionality & Mechanics
  • reactor/after and reactor/every schedule nanosecond deadlines
  • net/poll-wake interrupts blocking poll-wait from worker threads
  • Bridges CPU-bound spawn workers cleanly back to the I/O loop
Async Server
web/serve-reactor
lib/web.vk
Component 5 of 6
Architectural Role & Purpose

Serves concurrent HTTP/1.1 keep-alive connections and slow clients on a single reactor.

Contextual Description & System Interaction

Drop-in upgrade from web/serve-loop to non-blocking multiplexed serving.

Core Functionality & Mechanics
  • Incremental header/body buffering per connection slot
  • Enforces header size limits and idle keep-alive timeouts
  • Runs existing web/App routes and middleware unchanged
Async Client
net/client/request-batch
lib/net/client.vk
Component 6 of 6
Architectural Role & Purpose

Executes dozens of concurrent HTTP requests in parallel over one readiness reactor.

Contextual Description & System Interaction

Ideal for API gateways, health checkers, and distributed fan-out.

Core Functionality & Mechanics
  • Non-blocking TCP connect + incremental response assembly
  • Per-batch deadline enforcement via reactor timer wheel
  • get-many fetches N upstream endpoints in 1 round-trip window

Every reactor operation is gated behind the .net capability (allow-caps = [.net] in veko.vk) and compiles to the native kernel readiness primitive of each target:

Target Platform Underlying Kernel / Sandbox Mechanism Cross-Thread Wakeup (reactor/wake-handle)
Linux x86_64 (--target=linux-x64) epoll_create1 / epoll_ctl / epoll_pwait (zero-libc syscalls) eventfd2 (EFD_NONBLOCK | EFD_CLOEXEC)
Linux arm64 (--target=linux-arm64) epoll_create1 / epoll_ctl / epoll_pwait (zero-libc syscalls) eventfd2 (EFD_NONBLOCK | EFD_CLOEXEC)
macOS Apple Silicon (--target=macos-arm64) kqueue / kevent (EVFILT_READ, EVFILT_WRITE) EVFILT_USER (NOTE_TRIGGER)
Windows x64 & ARM64 (--target=win-x64 / --target=win-arm64) Win32 IOCP (CreateIoCompletionPort / GetQueuedCompletionStatus) + WSAPoll PostQueuedCompletionStatus + loopback UDP wake
64-bit VKO VM (--vm) Delegates directly to host OS native reactor Host OS native wakeup
Wasm 3.0 Sandbox (--wasm) wasi:sockets@0.3.0 net-poll + wasi:clocks@0.3.0 In-sandbox wake flag

2. Core Low-Level Builtins (net/poll-* & net/try-*)

All 11 non-blocking reactor builtins require the .net capability and preserve the .secret firewall (net/try-write rejects .secret buffers both statically and at runtime):

Builtin Arity Return Description
net/poll-new 0 i64 Allocates a new OS readiness poller handle.
net/poll-ctl 5 enum (poller, op, fd, events, token) — op: 1=ADD, 2=MOD, 3=DEL; events: 1=READ, 2=WRITE.
net/poll-wait 2 block (poller, timeout_dur) — returns a block of [token mask] pairs (1=READ, 2=WRITE, 4=ERR, 8=HUP).
net/poll-wake 1 enum (poller) — thread-safe wakeup of a thread blocked in net/poll-wait.
net/poll-close 1 enum (poller) — closes OS poller handles and releases internal slabs (idempotent).
net/set-nonblock 2 enum (sock, enabled bool) — toggles O_NONBLOCK / FIONBIO.
net/connect-tcp/nonblock 2 i64 (host, port) — initiates non-blocking TCP connect (EINPROGRESS / WSAEWOULDBLOCK succeeds).
net/sock-error 1 i64 (sock) — queries SO_ERROR via getsockopt (0 = connected/healthy).
net/try-accept 1 i64 (listener) — returns client socket >= 0, -1 if would-block, or err.
net/try-read-into 3 i64 (sock, mut buf, max_n) — appends up to max_n bytes into mut buf; returns > 0 bytes read, 0 on EOF, -1 if would-block, or err.
net/try-write 2 i64 (sock, data) — writes without blocking; returns >= 0 bytes sent, -1 if would-block, or err (blocks .secret).

3. Using lib/reactor.vk (Event Loop, Timers & Cross-Thread Wakeup)

lib/reactor.vk provides both pull-mode polling (idiomatic when mutating local single-owner connection tables with zero closure capture limits) and callback-mode dispatching (reactor/register-cb, reactor/after-cb, reactor/tick, reactor/run).

Timers & Cross-Thread spawn Wakeup

Because spawn workers are shared-nothing and cannot capture mut r, call reactor/waker r to extract a copyable i64 waker handle and pass it to any worker thread:

VEKO
use [reactor]

mut r = reactor/new
defer [ _ = reactor/close mut r ]

w = reactor/waker r
tid = reactor/after mut r 25ms

worker = spawn [
    time/sleep 5ms
    _ = reactor/wake-handle w
    .done
]

// Wakes early (~5ms) instead of sleeping for 2s
evs = reactor/poll mut r 2s
_ = task/await worker

// Poll until timer #tid fires
mut fired = false
while not fired [
    _ = reactor/poll mut r 25ms
    due = reactor/due-timers mut r
    mut i = 0
    while i < (len due) [
        if due[i] == tid [ fired = true ]
        i = i + 1
    ]
]

Pull-Mode Readiness Helpers

  • reactor/EV-READ (1), reactor/EV-WRITE (2), reactor/EV-ERR (4), reactor/EV-HUP (8), reactor/EV-RW (3)
  • reactor/readable? ev, reactor/writable? ev, reactor/errored? ev, reactor/closed? ev
  • reactor/register mut r fd events -> token
  • reactor/modify mut r token events -> .ok
  • reactor/unregister mut r token -> .ok
  • reactor/after mut r delay / reactor/every mut r interval / reactor/cancel-timer mut r tid

4. Non-Blocking HTTP/1.1 Server (web/serve-reactor & web/serve-async)

lib/web.vk includes a single-threaded, reactor-driven HTTP/1.1 server that multiplexes many concurrent connections over one OS thread. Slow or stalled clients (such as a peer pausing mid-header) never block other requests, and per-connection idle timeouts plus header/body size limits protect server memory automatically:

VEKO
use [web]

mut app = web/new-app
web/use-security-headers mut app
web/get mut app '/health' fn [req web/Request] web/Response [
    web/json-resp 200 { status = 'ok', path = req.path }
]

ln = net/listen-tcp .ip '127.0.0.1:8080'
opts = web/AsyncServerOpts {
    max_requests     = 0       // 0 = serve indefinitely
    read_timeout     = 10s
    tick_timeout     = 25ms
    max_header_bytes = 65536
    max_body_bytes   = 4194304
}
_ = web/serve-reactor ln app opts

For quick tests or bounded batch runs, use the convenience wrapper web/serve-async ln app 100.


5. Concurrent Non-Blocking HTTP/1.1 Client (net/client/request-batch & get-many)

lib/net/client.vk can fan out dozens of HTTP/1.1 requests simultaneously on a single reactor thread with per-request deadlines and transparent gzip/deflate decompression:

VEKO
use [hc = net/client]

reqs = [
    (hc/AsyncRequest { method = 'GET',  url = 'http://127.0.0.1:8080/items/1', timeout = 5s })
    (hc/AsyncRequest { method = 'GET',  url = 'http://127.0.0.1:8080/items/2', timeout = 5s })
    (hc/AsyncRequest { method = 'POST', url = 'http://127.0.0.1:8080/echo', body = (bytes/from-str 'ping'), timeout = 5s })
]

resps = hc/request-batch reqs
// resps[i] is either an `hc/HttpResponse` or `err` in matching input order

For parallel GET fan-out with shared options, use hc/get-many ['http://...' 'http://...'] (hc/RequestOpts { timeout = 5s }).


6. Non-Blocking Sockets (lib/io/net.vk) & Incremental WebSockets (lib/net/websocket.vk)

  • lib/io/net.vk:
    • inet/listen-nonblock addr — binds TCP listener and enables non-blocking mode
    • inet/dial-tcp-nonblock host port — starts non-blocking TCP connect
    • inet/set-nonblock sock enabled / inet/sock-error sock
    • inet/try-accept ln / inet/try-read-into sock mut buf max_n / inet/try-write sock data / inet/try-write-from sock data offset
  • lib/net/websocket.vk:
    • ws/try-decode-frame raw — incrementally parses RFC 6455 frames from a non-blocking receive buffer, returning FrameTry { complete = false, ... } until a full frame has arrived.

7. Running the Full End-to-End Example

See examples/29_async_reactor_http_server_and_client.vk for a complete demonstration covering cross-thread wakeups, timers, slow-client isolation, 4-way concurrent HTTP batching, secret firewall checks, and incremental WebSocket framing:

POWERSHELL
# Run on 64-bit VKO VM
veko run --vm --allow-net --allow-listen --allow-private-net examples/29_async_reactor_http_server_and_client.vk

# Compile & run natively (Win64 IOCP+WSAPoll or Linux epoll+eventfd2)
veko compile --native examples/29_async_reactor_http_server_and_client.vk -o dist/ex29.exe
./dist/ex29.exe

# Cross-compile for Windows ARM64, Linux x86_64, Linux arm64, or macOS Apple Silicon
veko compile --native --target=win-arm64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-win-arm64.exe
veko compile --native --target=linux-x64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-linux-x64
veko compile --native --target=linux-arm64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-linux-arm64
veko compile --native --target=macos-arm64 examples/29_async_reactor_http_server_and_client.vk -o dist/ex29-macos-arm64


Part IX: Durable Objects & Durable Workflows Guide

Veko 1.0 includes a zero-dependency Durable Objects (lib/durable/object.vk) and Durable Workflows (lib/durable/workflow.vk) library layered directly over lib/db/kv.vk's CRC-32-verified Write-Ahead Log (WAL). Every state transition, alarm, inbox message, step checkpoint, signal, and saga compensation is committed atomically in db/kv batches and survives process restarts and crashes cleanly.


1. Architecture Over lib/db/kv.vk

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

Both abstractions share one single embedded db/kv file (or separate stores per service) using clean, lexicographically sorted key prefixes:

Key Prefix Owner Stored Payload (codec/vbin)
do/<ns>/<id>/meta durable/object Version counter, timestamps, inbox sequence counter, active alarm deadline
do/<ns>/<id>/kv/<field> durable/object Individual durable state fields
do/<ns>/<id>/inbox/<seq> durable/object Monotonic FIFO mailbox messages (with attempt counters & visibility deadlines)
do_alarm/<ns>/<id> durable/object Indexed durable alarm schedule for O(k) poll-due-alarms
do_dlq/<ns>/<id>/<seq> durable/object Poison-message Dead-Letter Queue (list-dead-letters)
wf/<id>/meta durable/workflow Run status (.running, .waiting, .completed, .failed, .compensated), wake deadlines, worker lease
wf/<id>/step/<name> durable/workflow Memoized step result, retry attempt count, backoff deadline, or durable timer
wf/<id>/event/<name> durable/workflow External signal payload delivered via send-event
wf/<id>/comp/<seq> durable/workflow LIFO saga compensation journal entries
wf/<id>/log/<seq> durable/workflow Chronological execution audit trail
wf_dlq/<id> durable/workflow Dead-Letter Queue entry for exhausted workflows (requeue-dead-letter)

2. Durable Objects (lib/durable/object.vk)

A Durable Object is a named, single-writer, versioned stateful actor ((namespace, id)). All mutations commit atomically alongside the object's version counter.

Transactional Actor Turns (mutate) with Automatic Rollback

VEKO
use [d = durable, dobj = durable/object]

mut db = d/open-store 'state.vkkv'
mut acct = d/object mut db 'account' 'acct-001'
_ = dobj/put-fields mut db mut acct { owner = 'Alice', balance = 500 }

// Atomic turn: succeeds and increments acct.version in one WAL batch
bal = dobj/mutate mut db mut acct fn [st] [
    cur = as-i64 (map/get/or st 'balance' [ 0 ])
    if cur < 120 [ return (err 'insufficient funds') ]
    mut next = st
    map/set mut next 'balance' (cur - 120)
    { state = next, result = (cur - 120) }
]

If the handler returns err, zero keys are written and acct.version stays untouched.

Durable Alarms, Batch Enqueue & Transactional process-inbox with DLQ

Alarms and inbox messages are persisted in the WAL so they survive restarts. Use enqueue-batch for single-fsync multi-message writes, mutate-cas for optimistic compare-and-swap version checks across concurrent handles, and process-inbox (InboxOpts) to commit handler state updates and message deletion in one atomic WAL batch—automatically backing off failed messages and routing poison messages exceeding max_attempts into do_dlq/<ns>/<id>/<seq>:

VEKO
use [d = durable, dobj = durable/object]

_ = dobj/set-alarm mut db mut acct 30s 'billing-reconcile'
_ = dobj/enqueue-batch mut db mut acct [
    { kind = 'credit', payload = 250 }
    { kind = 'debit',  payload = 75 }
]

stats = dobj/process-inbox mut db mut acct (dobj/InboxOpts {
    max_messages = 32
    max_attempts = 3
    base_backoff = 100ms
}) fn [st msg] [
    bal0 = as-i64 (map/get/or st 'balance' [ 0 ])
    delta = if msg.kind == 'credit' [ as-i64 msg.payload ] else [ 0 - (as-i64 msg.payload) ]
    if (bal0 + delta) < 0 [ return (err 'overdraft') ]
    mut next = st
    map/set mut next 'balance' (bal0 + delta)
    next
]

due  = dobj/poll-due-alarms mut db 'account'
dlqs = dobj/list-dead-letters db acct

3. Durable Workflows (lib/durable/workflow.vk)

A Durable Workflow executes multi-step business logic with exact-once step memoization: if the process crashes halfway through a workflow and replays from the top, already-completed steps return their persisted checkpoints from db/kv without re-executing side effects.

Memoized Steps, Retries, Signals, Timers & LIFO Sagas

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

mut db = d/open-store 'workflows.vkkv'
mut run = d/workflow mut db 'ord-77' 'fulfill-order' { sku = 'VEKO-PRO', qty = 2 }

// 1. Memoized step: runs once, replays from db/kv on restart
res_id = wf/step mut db mut run 'reserve-inventory' fn [] [
    'res-901'
]

// 2. Durable retry with backoff & persisted attempt count
quote = wf/step-with-retry mut db mut run 'fetch-quote' 3 100ms fn [attempt] [
    if attempt < 2 [ return (err 'transient carrier timeout') ]
    { carrier = 'fastpost', cents = 1299 }
]

// 3. Suspend waiting for an external webhook signal
sig = wf/wait-event mut db mut run 'payment-confirmed'
if not sig.ready [
    // Workflow is durably parked in .waiting until `wf/send-event` arrives
    return .ok
]

// 4. Durable timer that survives restarts
if not (wf/sleep-until mut db mut run 'cooling-window' 5s) [
    return .ok
]

_ = wf/complete mut db mut run { reservation = res_id, receipt = sig.payload.receipt }

LIFO Saga Compensations, Batch Steps, Worker Leases & Workflow DLQ

Register compensating actions as forward steps succeed. If a downstream step fails permanently, call wf/run-compensations to unwind in strict reverse (LIFO) order:

VEKO
_ = wf/record-compensation mut db mut run 'release-inventory' res_id
_ = wf/record-compensation mut db mut run 'void-payment' auth_id

// On unrecoverable failure:
n = wf/run-compensations mut db mut run fn [comp_name data] [
    println (str/join ['undo ' comp_name ': ' (mold data)] '')
    .ok
]

For high-throughput distributed workers:

  • wf/step-policy & Dead-Letter Queue (wf_dlq/*): Configure wf/RetryPolicy { max_attempts, base_backoff, max_backoff, backoff_factor, dead_letter = true } so non-parked steps persist exponential backoff deadlines (status = .waiting, zero thread blocking!) and move exhausted runs to wf_dlq/<id>. Inspect via wf/list-dead-letters db and replay after fixing an upstream outage via wf/requeue-dead-letter mut db 'ord-77'.
  • wf/step-batch: Executes and checkpoints multiple deterministic sub-steps in a single WAL fsync commit (wf/step-batch mut db mut run [['validate' fn [] [...]] ['enrich' fn [] [...]]]).
  • wf/wait-event-timeout: Parks a workflow awaiting an external webhook signal up to a durable deadline (wf/wait-event-timeout mut db mut run 'approval' 24h), returning { ready = false, timed_out = true } if the deadline elapses first.
  • Distributed Worker Leases (poll-runnable & claim-run): Multiple worker processes poll ready workflows whose sleep/retry timers or signals have matured (wf/poll-runnable db 16) and acquire time-bounded leases (wf/claim-run mut db run_id 'worker-01' 30s) before resuming execution.

Run the end-to-end crash-and-replay demonstration in examples/32_durable_objects_and_workflows.vk:

POWERSHELL
veko run examples/32_durable_objects_and_workflows.vk
veko run --native examples/32_durable_objects_and_workflows.vk

Part X: Terminal UI, Native Desktop UI Toolkit, PNG Graphics, and Opt-In FFI Guide

Veko ships a complete, capability-isolated stack for terminal dashboards (lib/tui.vk), zero-dependency 2D software graphics, RFC 2083 PNG encoding/decoding (lib/image/png.vk), mixed-case proportional typography (lib/ui/font.vk), 1D/2D flex & grid layout (lib/ui/layout.vk), 33 immediate-mode desktop & studio widgets (lib/ui/widgets.vk), native window surfaces across Win32, zero-libc Linux Wayland (wl_shm) & X11, macOS arm64 (AppKit / CoreGraphics), and Wasm <canvas> with keyboard focus traversal, OS clipboard & Hi-DPI scaling (lib/ui.vk, lib/ui/wayland.vk, lib/ui/x11.vk), and opt-in foreign library interop (lib/ffi.vk honoring VEKO_LIB + veko bindgen).


1. Capability Model & Zero-Bloat Guarantees

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

Every layer in Veko's UI and FFI stack follows least-privilege capability isolation:

Layer Modules Required Capability Native Binary Footprint Wasm 3.0 (--wasm)
Terminal UI (TUI) tui None Pure ANSI/VT100; zero GUI DLLs Supported
2D Canvas, Font, Layout, Wayland/X11 Framing, PNG & 33 Studio Widgets ui/canvas, ui/font, ui/layout, ui/wayland, ui/x11, ui/widgets, image/png None (allow-caps = []) Pure Veko RGBA32 rasterizer, Wayland & X11 wire codecs + zlib PNG; zero GUI DLLs Supported
Native Window, Keyboard/Mouse Events, OS Clipboard & Hi-DPI Surface ui (ui/open, ui/present, ui/poll-events, ui/clipboard-get, ui/clipboard-get/secret, ui/clipboard-set, ui/dpi-scale, ui/close) .ui (allow-caps = [.ui]) Win32 Per-Monitor V2 Hi-DPI (--gui sets PE Subsystem = 2); Linux zero-libc Wayland (wl_shm + memfd_create + SCM_RIGHTS) cascading to X11 over AF_UNIX; macOS arm64 AppKit/CoreGraphics Retina NSWindow (linked only when .ui is active); headless fallback via VEKO_HEADLESS=1 Supported (shared linear-memory <canvas> + event ring, 0 leaked slabs)
Opt-In Foreign Libraries ffi (ffi/open, ffi/sym, ffi/call, ffi/close) + veko bindgen .ffi (denied by default; requires --allow-ffi, -C ffi, or allow-caps = [.ffi]) Resolves search directories from VEKO_LIB; Win64 kernel32.dll; Linux x86_64 opt-in dynamic ELF64 (libc.so.6) only when .ffi is active; macOS arm64 libSystem Strictly forbidden (zero-trust sandbox)

2. Terminal UI (lib/tui.vk)

lib/tui.vk provides a double-buffered ANSI/VT100 screen grid with 24-bit TrueColor RGB cells, style bitmasks, boxes, progress bars, sparklines, tables, tui/parse-key input decoding, and a diffing frame encoder (tui/render-diff) that only transmits modified cells:

VEKO
use [tui]

mut scr = tui/new-screen 60 12
tui/clear mut scr tui/color-white tui/color-surface
tui/draw-box mut scr 0 0 60 12 'Node Monitor' .rounded tui/color-cyan tui/color-surface
tui/draw-progress mut scr 2 3 30 75 tui/color-emerald tui/color-slate tui/color-surface
frame_ansi = tui/render-diff mut scr

3. 2D Canvas, Typography, Flex/Grid Layout & Lossless PNG (ui/*, image/png)

  • ui/canvas: Porter-Duff SRC_OVER RGBA32 rasterizer with set-clip / reset-clip scissor rectangles, fill-rounded-rect, stroke-rounded-rect, draw-line-smooth, fill-circle, stroke-circle, encode-bmp, and encode-ppm.
  • ui/font: Crisp mixed-case proportional & monospace typography (A-Z, a-z with true ascenders/descenders, 0-9, symbols, and bullet masks) across body (size = 1), heading (size = 2), and display (size = 3) scales, plus draw-truncated ellipsis clipping.
  • ui/layout: 1D/2D constraint solver (px, flex, flex-row, flex-col, grid, split-h, split-v, ClipStack) usable standalone or via ui/widgets.
  • image/png: Pure-Veko RFC 2083 RGBA32 PNG encoder and decoder (png/encode, png/encode-rgba, png/decode, png/decode-rgba) using adaptive per-scanline filtering and compress/deflate.
  • ui/x11: Pure-Veko X11 Release 11 wire-protocol codec (build-setup, parse-setup, plan-bands, build-put-image-band, decode-event) backing Veko's zero-libc Linux desktop window surface (AF_UNIX /tmp/.X11-unix/X<n>, .Xauthority MIT-MAGIC-COOKIE-1, and chunked scanline-band PutImage <= 128 KB).

4. The 33-Widget Immediate-Mode Desktop & Studio Toolkit (lib/ui/widgets.vk)

lib/ui/widgets.vk renders studio-grade Light-Mode and Dark-Mode desktop interfaces directly into a cv/Canvas with zero GC pauses, zero host capabilities (allow-caps = []), and zero per-frame pixel buffer clones (demos/widget_gallery):

Veko Studio Widget Gallery — Form Inputs, Masked .secret Fields, Dropdowns, Chips & Code Editor

Veko Studio Widget Gallery — Text Selection Highlight, .secret-Firewalled Clipboard & Per-Monitor V2 Hi-DPI Scaling

Keyboard Focus Ring, OS Clipboard, .secret Hygiene & Hi-DPI Scaling

  • Full Keyboard Navigation & Focus Ring (begin-frame / end-frame): Every interactive widget registers in a deterministic per-frame focus ring. Tab and Shift+Tab cycle focus_id with crisp theme accent outlines, while Space/Enter activate buttons/checkboxes/toggles, arrow keys adjust sliders/radios/dropdowns/tabs/lists/trees, and Escape dismisses modals and palettes. lib/ui.vk exposes EV-KEY-DOWN, EV-KEY-UP, MOD-SHIFT/CTRL/ALT/SUPER, and KEY-F1..F12 / navigation constants across Win32, Wayland, X11, AppKit, and Wasm <canvas>.
  • OS Clipboard & .secret Outbound Firewall: text-input, text-area, and code-editor support keyboard selection (Shift+Arrows/Home/End) and system clipboard shortcuts (Ctrl+A, Ctrl+C, Ctrl+X, Ctrl+V). ui/clipboard-set rejects .secret values statically and at runtime, while ui/clipboard-get/secret reads pasted secrets directly into zeroized-on-drop .secret memory.
  • Per-Monitor V2 Hi-DPI & Wasm <canvas>: ui/dpi-scale queries the active window's percentage scale factor (100, 125, 150, 200) across Win32 Per-Monitor V2 (GetDpiForWindow), Linux Wayland/X11, macOS Retina, and browser devicePixelRatio.

Studio IDE Widgets (code-editor, command-palette, file-picker, split-pane-state)

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

mut st  = w/new-state
mut ed  = w/new-editor 'pub greet = fn [who str] str [\n    `Hello, {who}!`\n]'
mut pal = w/new-palette
th      = w/light-theme
mut c   = cv/new-canvas 800 480

w/begin-frame mut st
// Multi-line Veko-highlighted code editor with line numbers, selection, clipboard & 64-step Ctrl+Z / Ctrl+Y undo/redo
_ = w/code-editor mut c mut st 'main-editor' (w/Rect { x = 16, y = 16, w = 768, h = 360 }) mut ed th '' ''

// Fuzzy command palette overlay (`Ctrl+P` / `Ctrl+K`)
cmd_id = w/command-palette mut c mut st 'studio-pal' (w/Rect { x = 0, y = 0, w = 800, h = 480 }) mut pal [
    w/CommandItem { id = 'run',   label = 'Run Active Buffer', shortcut = 'F5' }
    w/CommandItem { id = 'check', label = 'Strict Type Check', shortcut = 'Ctrl+Shift+B' }
] th
w/end-frame mut st

To browse workspace files without adding .fs capabilities to ui/widgets, pair fs/list-entries dir (in lib/fs.vk) with the pure w/file-picker modal (w/FilePickerState, w/FileEntry), and resize multi-pane layouts interactively with w/split-pane-state.

Complete Widget Catalog

  1. Surfaces & KPI Cards: panel, panel-body, label, heading, button (with /primary), icon-button, badge, stat-card.
  2. Forms & .secret Inputs: text-input (with /secret bullet mask), secret-input (operates directly on mut secret bytes without str conversion), text-area (with line-number gutter), checkbox, toggle-switch, radio-group, slider, progress-bar (with /label), dropdown, chip-group.
  3. Navigation, Tables & Trees: tabs, begin-scroll / end-scroll (with mouse wheel EV-WHEEL & scrollbar), list-view, select-list, data-table (zebra striping & auto-pill status cells), tree-view (disclosure triangles & badges), split-pane, split-pane-state (interactive mouse drag).
  4. Studio IDE & Overlays: code-editor (EditorState, Veko syntax highlighting, Ctrl+Z/Ctrl+Y undo/redo, auto-indent), command-palette (PaletteState, fuzzy search + shortcuts), file-picker (FilePickerState, breadcrumbs + extension filter), menu-bar, context-menu, modal, toast, tooltip.
  5. Charts & Telemetry: sparkline, bar-chart, line-chart (multi-series anti-aliased curves + legend).

Veko Studio Widget Gallery — Hierarchical Tree View, Multi-Column Data Table & Scrollable Inspector

Veko Studio Widget Gallery — KPI Stat Cards, Bar Chart, Multi-Series Line Chart & Sparklines

Veko Studio Widget Gallery — Nested Split Panes, Context Menu, Tooltip, Modal Dialog & Toast

Veko Canvas Workbench — Light-Mode Cluster Topology, Sketch Pad, Durable Sprint KV & Profiler

Running the Desktop Showcases

POWERSHELL
# Run deterministic cross-runtime verification or export Light-Mode PNGs
veko demos/widget_gallery
veko demos/widget_gallery -- --export-dir docs/screenshots

# Launch live interactive Win32 desktop windows (EV-KEY, EV-TEXT, EV-WHEEL, EV-RESIZE, BTN-RIGHT)
veko demos/widget_gallery -- --live
veko demos/canvas_workbench -- --live

5. Opt-In Foreign Library Boundary (lib/ffi.vk) & veko bindgen

Veko's .ffi capability calls native shared libraries (.dll, .so, .dylib) via zero-W^X static AOT C-ABI trampolines while keeping .ffi denied by default, permanently blocked on --wasm, and walled off from .secret data.

Generating Wrapper Modules Automatically (veko bindgen)

Instead of hand-writing symbol lookups and struct offsets, point veko bindgen at a C header file to generate #define constants, Veko struct definitions, little-endian pack-* helpers, and typed ffi/call-c wrappers:

POWERSHELL
veko bindgen path/to/library_api_header -l sqlite3 -o src/sqlite_ffi.vk
veko check --strict-types -C ffi src/sqlite_ffi.vk

Manual Foreign Calls & C-Struct Packing

VEKO
use [ffi]

mut buf = bytes/with-cap 32
ffi/pack-i32 mut buf -42
ffi/pack-u32 mut buf 0x12345678
ffi/pad-align mut buf 8
ffi/pack-i64 mut buf 1735689600000
ffi/pack-cstr mut buf 'veko-ffi'

is_win = (os/getenv/or 'OS' ['']) == 'Windows_NT'
lib = ffi/open-lib (if is_win [ 'kernel32.dll' ] else [ 'libc.so.6' ])
pid_sym = ffi/resolve lib (if is_win [ 'GetCurrentProcessId' ] else [ 'getpid' ])
pid = ffi/call-c pid_sym []
_ = ffi/close-lib lib

Next Steps


Part XI: Performance, Hardware Intrinsics & AArch64 Cross-Compilation Guide

Veko delivers predictable, low-latency native execution strictly without a JIT compiler and with zero W^X (write-then-execute) memory pages. Every native binary is compiled ahead-of-time (AOT) directly from Veko's 64-bit VKO intermediate representation into standalone machine code across 5 zero-dependency OS/CPU targets — Windows x86_64 (win-x64), Windows 11 ARM64 (win-arm64), Linux x86_64 (linux-x64), Linux AArch64 (linux-arm64), and macOS Apple Silicon (macos-arm64) — with zero external C compiler, LLVM, libc, or crypto library dependencies.


1. Strict No-JIT & Zero-W^X Execution Model

CODEGEN & BINARY LINKERS

64-Bit VKO ISA, Hardware SIMD & Four-Target Native Binary Emitters

Zero-JIT, zero-W^X compilation from typed ASTs to superinstruction bytecode, x86_64, and AArch64 executables.

Interactive SVG • Click any node (6 components)
IR & BYTECODE TRACK vko_emit.vk + oro_vm.vk X86_64 NATIVE BACKEND x64_enc.vk + native_emit.vk AARCH64 NATIVE BACKEND arm64_enc.vk + arm64_emit.vk VKO1 words x86_64 code ARM64 code Shared AST PAL parity Bytecode IR 64-Bit VKO Emitter op:u8 | flags:u8 | a:u16 | bx:u32 VM Engine VM Superinstructions Zero-JIT Dispatch Fusion x86_64 Codegen x86_64 Machine Emitter CPUID AVX2 / SSE2 / AES-NI x86_64 Linkers Win64 PE32+ & Linux ELF64 pe_emit.vk + elf_emit.vk ARM64 Codegen AArch64 Machine Emitter ARMv8-A + NEON-ready PAL ARM64 Linkers Linux ELF64 & macOS Mach-O elf_emit.vk + macho_emit.vk
Components:
Bytecode IR
64-Bit VKO Emitter
vko_emit.vk
Component 1 of 6
Architectural Role & Purpose

Compiles ASTs into fixed-width 64-bit instructions serialized as portable 'VKO1' binaries.

Contextual Description & System Interaction

Eliminates narrow bytecode limits so the 39-module compiler runs effortlessly on the VM.

Core Functionality & Mechanics
  • Supports 65,535 locals per frame and 4B constant/jump offsets
  • Emits TRY_OR and DEFER_PUSH structured unwind scopes
  • Validates spawn capture isolation at compile time
VM Engine
VM Superinstructions
oro_vm.vk
Component 2 of 6
Architectural Role & Purpose

Fuses hot local-load, arithmetic, comparison, and branch sequences in pure AOT code.

Contextual Description & System Interaction

Delivers fast interpreter performance while remaining 100% compatible with iOS/hardened kernels.

Core Functionality & Mechanics
  • Strict No-JIT design: zero RWX pages on every platform
  • Accelerates inner loops and crypto rounds on Track A
  • Powers veko repl and instant .vk script execution
x86_64 Codegen
x86_64 Machine Emitter
x64_enc.vk native_emit.vk
Component 3 of 6
Architectural Role & Purpose

Lowers typed ASTs directly to x86_64 machine code with 79-group dead-code elimination.

Contextual Description & System Interaction

Generates compact native machine code in milliseconds without invoking clang, gcc, or link.exe.

Core Functionality & Mechanics
  • Uses CPUID dispatch for AVX2/SSE2 byte scans/XOR and AESENC
  • Unboxes tight integer/float loops into native CPU registers
  • Emits static C-ABI trampolines only when .ffi is enabled
x86_64 Linkers
Win64 PE32+ & Linux ELF64
pe_emit.vk elf_emit.vk
Component 4 of 6
Architectural Role & Purpose

Writes standalone Windows .exe and static zero-libc Linux x86_64 executables.

Contextual Description & System Interaction

Produces clean, dependency-free binaries ready for Windows desktops and Linux containers.

Core Functionality & Mechanics
  • Win64 imports only kernel32/ws2_32 (+ user32/gdi32 only on .ui; --gui)
  • Linux x86_64 emits 100% static ELF64 (dynamic libc.so.6 only on .ffi)
  • Verified S1 == S2 bit-identical self-hosting on both OSes
ARM64 Codegen
AArch64 Machine Emitter
arm64_enc.vk arm64_emit.vk
Component 5 of 6
Architectural Role & Purpose

Encodes fixed 32-bit ARM64 instructions with dedicated callee-saved runtime registers.

Contextual Description & System Interaction

Brings first-class native performance to AWS Graviton, Raspberry Pi, and Apple Silicon.

Core Functionality & Mechanics
  • Maps ORO 16B Value pairs cleanly onto X0..X28 register file
  • Shares identical 16B SlabHdr and 12-bucket allocator invariants
  • Cross-compiles from Windows or Linux hosts with zero SDKs
ARM64 Linkers
Linux ELF64 & macOS Mach-O
elf_emit.vk macho_emit.vk
Component 6 of 6
Architectural Role & Purpose

Emits static Linux EM_AARCH64 ELF64 and ad-hoc SHA-256 signed 16 KiB Apple Silicon Mach-O.

Contextual Description & System Interaction

Completes Veko 1.0's four-target native cross-compilation matrix.

Core Functionality & Mechanics
  • Linux arm64 uses raw syscalls + clone/futex + epoll (S1 == S2 verified)
  • macOS arm64 emits LC_MAIN, libSystem.B.dylib, and LC_CODE_SIGNATURE
  • 16 KiB segment alignment runs natively on macOS M1/M2/M3/M4

Across all three execution tracks, Veko enforces strict separation between writable memory and executable code:

  • Track A (--vm / .vko): The pure-Veko 64-bit bytecode VM (oro_vm.vk) uses fused superinstructions (LOAD_CONST_ADD, LOAD_CONST_LT_JMP_FALSE, LOCAL_INC, LOAD_LOCAL_INDEX, LOAD_LOCAL_LEN), shared devirtualization, guarded leaf inlining, optional --fuel=<n> instruction quotas, and .secret-preserving native fast-paths for modular big-integer/Curve25519/Keccak-f[1600]/SHA-2 kernels so even interpreted veko run completes full post-quantum TLS 1.3 HTTPS handshakes in milliseconds without allocating executable heap pages.
  • Track B (--wasm / vvm): Compiles to validated WebAssembly 3.0 with hardware f64.sqrt, bulk memory ops, unboxed i64/f64 loops, and capability-confined HostSandbox isolation.
  • Track C (--native): Emits standalone OS executables directly for five OS/CPU architectures and platforms:
    • --target=win-x64 — Windows x86_64 64-bit PE32+ executable (kernel32.dll / ws2_32.dll only, optional --gui)
    • --target=win-arm64 — Windows 11 ARM64 64-bit PE32+ (0xAA64) executable (kernel32.dll / ws2_32.dll only, optional --gui — Snapdragon X Elite/Plus, Surface Pro/Laptop, Windows on ARM VMs)
    • --target=linux-x64 — Static zero-libc Linux x86_64 ELF64 executable (direct Linux syscalls)
    • --target=linux-arm64 — Static zero-libc Linux AArch64 (arm64) ELF64 executable (direct asm-generic Linux syscalls — AWS Graviton, Ampere, Raspberry Pi 5)
    • --target=macos-arm64 — 16 KiB-aligned Apple Silicon M1–M4 Mach-O MH_EXECUTE binary with dyld chained fixups, /usr/lib/libSystem.B.dylib stubs, and automatic pure-Veko SHA-256 ad-hoc LC_CODE_SIGNATURE

On x86_64 native targets, startup performs a single read-only CPUID + XGETBV probe (SSE2, AVX2, AES-NI) and dispatches hot byte and cryptographic loops automatically to the widest supported instruction set—falling back cleanly to constant-time scalar code on older CPUs.


2. Hardware & Bulk Byte Intrinsics (3-Track Parity)

Six built-in primitives accelerate numeric, buffer-scanning, and cryptographic workloads across all three backends with bit-identical semantics:

Builtin Arity Description Native Hardware Acceleration
f64/sqrt 1 IEEE-754 double-precision square root SQRTSD (x86_64), FSQRT (AArch64), f64.sqrt (Wasm 3.0)
bytes/eq 2 Exact byte-buffer equality check AVX2 32B / SSE2 16B lanes (x86_64), 8B word loop (AArch64)
bytes/index-of 2 First byte offset of needle in haystack, or -1 AVX2 / SSE2 PMOVMSKB scan (x86_64), fast prefix scan (AArch64)
bytes/xor 2 Returns a new bytes buffer XORing two equal-length buffers AVX2 32B / SSE2 16B VPXOR/PXOR (x86_64), 8B EOR loop (AArch64)
bytes/xor! 2 In-place ORO mut XOR (bytes/xor! mut dst mask) with zero allocation AVX2 32B / SSE2 16B in-place vector XOR (x86_64), 8B EOR loop (AArch64)
bytes/aes-enc-block 2 Single-block AES-128/192/256 encryption (blk16, rk) Hardware AESENC/AESENCLAST (x86_64 AES-NI), constant-time branchless algebraic GF(2^8) fallback (AArch64 / non-AES-NI / Wasm / VM)

Example: Using Hardware & Bulk Intrinsics

VEKO
use [m = math, bits, hex = codec/hex, aes = crypto/aes]

// Hardware IEEE-754 square root (`math/sqrt` delegates to `f64/sqrt`)
root2 = f64/sqrt 2.0

// Bulk SIMD equality, search, and zero-allocation in-place XOR
hay = bytes/from-str 'veko-simd-acceleration-pipeline-sentinel-99'
idx = bytes/index-of hay (bytes/from-str 'sentinel-99')

mut payload = bytes/from-str '0123456789abcdef'
mask = bytes/fill 16 0x5a
_ = bytes/xor! mut payload mask
_ = bytes/xor! mut payload mask
ok = bytes/eq payload (bytes/from-str '0123456789abcdef')

// NIST FIPS-197 AES-256 block & AES-256-GCM AEAD (automatically uses AES-NI when present)
key = hex/decode '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'
pt = hex/decode '00112233445566778899aabbccddeeff'
ct = aes/encrypt-block key pt   // '8ea2b7ca516745bfeafc49904b496089'

// Table-driven IEEE 802.3 CRC32 (256-entry Sarwate table in `lib/bits.vk`)
sum = bits/crc32 (bytes/from-str '123456789')   // 0xcbf43926

Run the complete self-verifying demonstration (examples/28_simd_optimization_and_arm64_cross_compile.vk) across all tracks:

POWERSHELL
veko run examples/28_simd_optimization_and_arm64_cross_compile.vk
veko run --wasm --fuel=0 --check-slabs examples/28_simd_optimization_and_arm64_cross_compile.vk
veko run --native examples/28_simd_optimization_and_arm64_cross_compile.vk

3. Content-Addressed Incremental Cache & veko run --native

Veko accelerates both interactive type-checking and AOT native builds via a deterministic content-addressed cache under dist/.veko_cache/ (bypassable anytime with --no-cache):

  1. Frontend & Binary Cache (dist/.veko_cache/mod_v1/): Keyed by a SHA-256 digest over the compiler binary fingerprint, embedded 'VFS2' stdlib fingerprint (stdlib_vfs.bin, lazy per-module zlib decompression), target triple, --strict-types / --gui flags, and FNV-1a + mtime content hashes of all transitive modules.
  2. Warm Sub-50ms Turnaround: On a 42-module production server (veko-site, including TLS 1.3, HTTP/2, QUIC HTTP/3, and Zero-FFI SQLite), cold veko check completes in ~2.7s and warm veko check in ~43 ms; cold veko compile --native completes in ~9.7s and warm veko compile --native in ~48 ms. Pass --no-cache (used automatically by build.vk -- fixed-point) to force a full uncached rebuild and verify S1 == S2 bit-identical determinism.
  3. Native Codegen Fast-Paths (native_emit.vk & x64_enc.vk): Unboxed vstack loop conditions fuse while i < (len xs) into 3 machine instructions with zero [R13] stack spills or rt_release calls, inline bounds-checked bytes[i] loads, and patch x64 jump/call relocations in $O(L + F)$ in-place passes.

For scripts and benchmarks that want full native throughput without managing output paths manually, use veko run --native:

POWERSHELL
veko run --native benchmarks/bench_suite.vk
veko compile --native --no-cache src/main.vk -o dist/app.exe

4. Cross-Compiling to AArch64 (win-arm64, linux-arm64 & macos-arm64)

Every veko binary includes both the x86_64 and AArch64 native code generators and linkers built in. You can cross-compile from any host OS to any of the 5 supported targets in a single command—no cross-compilers, Docker toolchains, Visual Studio Build Tools, or Xcode SDKs are required.

Target Matrix

--target Architecture Binary Format Runtime ABI & Linking Signing / Permissions
win-x64 x86_64 PE32+ (.exe, 0x8664) kernel32.dll + ws2_32.dll IAT (--gui optional) Standard Windows x64 executable
win-arm64 AArch64 (arm64) PE32+ (.exe, 0xAA64) kernel32.dll + ws2_32.dll IAT (--gui optional) Native Windows 11 ARM64 executable (zero x64 emulation)
linux-x64 x86_64 Static ELF64 (ET_EXEC) Direct Linux syscalls (zero libc) Automatic 0o755 executable mode
linux-arm64 AArch64 (arm64) Static ELF64 (EM_AARCH64) Direct asm-generic Linux syscalls (zero libc) Automatic 0o755 executable mode
macos-arm64 AArch64 (arm64) 16 KiB Mach-O MH_EXECUTE dyld chained fixups + /usr/lib/libSystem.B.dylib stubs Built-in pure-Veko SHA-256 ad-hoc LC_CODE_SIGNATURE

Cross-Compile Commands

POWERSHELL
# Windows 11 ARM64 PE32+ (0xAA64) binary (Snapdragon X Elite/Plus, Surface Pro/Laptop, Windows on ARM VMs)
veko compile --native --target=win-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/app_win_arm64.exe

# Static Linux AArch64 (arm64) binary (runs on Raspberry Pi 4/5, AWS Graviton, Ampere, or QEMU)
veko compile --native --target=linux-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/app_linux_arm64

# Apple Silicon macOS arm64 binary (16 KiB pages + automatic ad-hoc SHA-256 LC_CODE_SIGNATURE)
veko compile --native --target=macos-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/app_macos_arm64

# Self-host the full Veko compiler itself for Windows arm64, Linux arm64, or macOS arm64
veko compile --native --target=win-arm64   src/main.vk -o dist/veko_win_arm64.exe
veko compile --native --target=linux-arm64 src/main.vk -o dist/veko_linux_arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/veko_macos_arm64

Deploying win-arm64 Binaries on Windows 11 on ARM

--target=win-arm64 emits a native AArch64 PE32+ (IMAGE_FILE_MACHINE_ARM64 = 0xAA64) executable using the Windows ARM64 AAPCS64 calling convention (X0..X7 integer arguments, X18 reserved for the Win32 TEB, ADRP+LDR Win32 IAT thunks). Binaries execute directly on Snapdragon X Elite/Plus workstations, Surface Pro/Laptop devices, and Azure/AWS Windows on ARM instances with zero Prism x64 binary-translation overhead, and veko run --native / veko compile --native auto-detect Windows ARM64 hosts automatically.

Testing linux-arm64 Binaries on x86_64 Hosts via QEMU

On Linux or Windows WSL2 (Ubuntu/Debian), install user-mode QEMU emulation and execute linux-arm64 binaries directly:

BASH
sudo apt-get update && sudo apt-get install -y qemu-user
qemu-aarch64 ./dist/app_linux_arm64

Deploying macos-arm64 Binaries on Apple Silicon

Apple Silicon (arm64) macOS requires every executable to be 16 KiB page-aligned and signed with at least an ad-hoc LC_CODE_SIGNATURE containing SHA-256 hashes of every 4 KiB code page. Veko's built-in Mach-O linker (macho_emit.vk) computes and embeds the full CS_MAGIC_EMBEDDED_SIGNATURE / CS_MAGIC_CODEDIRECTORY SHA-256 blob automatically (and unlinks any existing Mach-O target before writing to avoid APFS code-signing vnode cache SIGKILL), while veko run --native, veko compile --native, and veko doc --test --native auto-detect Apple Silicon (macos-arm64) and Linux AArch64 (linux-arm64) hosts out of the box without requiring --target, codesign, or Xcode.


5. Benchmarking Across All Three Tracks

Run Veko's reproducible benchmark suite (benchmarks/bench_suite.vk) to measure native, Wasm 3.0, and bytecode VM throughput on your machine:

POWERSHELL
veko run --native benchmarks/bench_suite.vk
veko run --wasm --fuel=0 benchmarks/bench_suite.vk
veko run benchmarks/bench_suite.vk

The suite benchmarks 9 real-world pure-Veko workloads: math/sqrt+sin, bits/crc32 (1 KiB), seq/sort (64 ints), regex/find-all, compress/gzip, crypto/sha3-256 (1 KiB), crypto/blake2b-256 (1 KiB), crypto/aes-256-gcm, and crypto/mlkem-512 post-quantum encapsulation.


Part XII: Runnable Examples & Showcase Applications

Every example in examples/ (42 runnable programs) and every multi-module showcase application in demos/ (6 complete applications, including the 29-widget demos/widget_gallery desktop UI suite) executes across Veko's three execution tracks: the 64-bit VKO bytecode VM (veko run), WebAssembly 3.0 sandbox (veko run --wasm), and standalone native executables (veko run --native or veko compile --native [--target=<win-x64|win-arm64|linux-x64|linux-arm64|macos-arm64>]).

SELF-HOSTING CONVERGENCE

Veko 1.0 Self-Hosted Toolchain & Triple-Target S1 == S2 Fixed Point

How the 39-module pure-Veko compiler compiles itself to bit-identical native binaries across architectures.

Interactive SVG • Click any node (4 components)
UNIFIED PURE-VEKO SOURCE src/ (39) + lib/ (79) DETERMINISTIC BOOTSTRAP CHAIN Reproducible S1 == S2 Proof Compile S1 Same source S1 builds S2 SHA-256 Bit-equal! Source Tree Self-Hosted Source 39 src/*.vk + 79 lib/*.vk Stage 1 Stage 1 Compiler (S1) veko compile --native src/main.vk Stage 2 Stage 2 Compiler (S2) S1 compiles src/main.vk -> S2 Release Gate Bit-Identical Fixed Point SHA-256(S1) == SHA-256(S2)
Components:
Source Tree
Self-Hosted Source
src/main.vk
Component 1 of 4
Architectural Role & Purpose

100% of lexer, parser, typechecker, VKO VM, Wasm emitter, x64/arm64 emitters, fmt, lsp, and docgen.

Contextual Description & System Interaction

Every tool in Veko is written in idiomatic Veko itself.

Core Functionality & Mechanics
  • Zero C, C++, Rust, or V compiler runtime dependencies
  • Deterministic map iteration and canonical binary headers
  • Single entry point src/main.vk drives every CLI subcommand
Stage 1
Stage 1 Compiler (S1)
native_emit.vk arm64_emit.vk
Component 2 of 4
Architectural Role & Purpose

Promoted host compiler compiles src/main.vk into a fresh Stage 1 native executable.

Contextual Description & System Interaction

Produces a clean candidate compiler binary for each target.

Core Functionality & Mechanics
  • Emits win-x64, linux-x64, linux-arm64, and macos-arm64 binaries
  • Embeds 79-group DCE and deterministic symbol layout
  • Zero timestamps or host path entropy in output sections
Stage 2
Stage 2 Compiler (S2)
pe_emit.vk elf_emit.vk
Component 3 of 4
Architectural Role & Purpose

Stage 1 executes natively (or under QEMU for arm64) to compile src/main.vk a second time.

Contextual Description & System Interaction

Proves the generated compiler faithfully reproduces its own machine code.

Core Functionality & Mechanics
  • Exercises the newly generated machine code on all 39 modules
  • Stress-tests ORO slab recycling across 100,000+ AST nodes
  • Emits Stage 2 binary without external host assistance
Release Gate
Bit-Identical Fixed Point
build.vk tests/run_tests.vk
Component 4 of 4
Architectural Role & Purpose

Byte-for-byte SHA-256 equality across Win64 PE32+, Linux x86_64 ELF64, and Linux AArch64 ELF64.

Contextual Description & System Interaction

Establishes mathematical reproducibility for Veko v1.0.0 releases.

Core Functionality & Mechanics
  • Plus verified 14/14 test suites across VM, Wasm, and Native
  • Zero leaked slabs verified via --wasm --check-slabs
  • Signed macOS arm64 Mach-O LC_CODE_SIGNATURE verified

1. Runnable Example Catalog (examples/)

Example File Focus Run Command
examples/01_basics_and_math.vk Rich literals (250ms, 4kb, .tcp), bitwise ops, ranges, loops veko run examples/01_basics_and_math.vk
examples/02_pipelines_and_json.vk use aliases, \ pipes, json/decode, filter/map/reduce, match veko run examples/02_pipelines_and_json.vk
examples/03_oro_buffers_and_errors.vk mut buffer loans, bytes/with-secret, defer, /or, recur veko run examples/03_oro_buffers_and_errors.vk
examples/04_macros_and_dialects.vk quote, compose/deep, parse-block, compile-time macro veko run examples/04_macros_and_dialects.vk
examples/05_closures_and_capabilities.vk Stateful ORO closures & explicit non-OOP capability records veko run examples/05_closures_and_capabilities.vk
examples/06_policy_firewall_compiler.vk Declarative parse-block policy compiler & stateful ORO rate-limiter veko run examples/06_policy_firewall_compiler.vk
examples/07_binary_frame_codec.vk Binary wire-protocol encoder/decoder, XOR checksum & ascii normalization veko run examples/07_binary_frame_codec.vk
examples/08_kv_store_and_audit_log.vk Single-owner ORO KV store, hash-chained recur audit log & secret zeroing veko run examples/08_kv_store_and_audit_log.vk
examples/09_concurrent_worker_pool.vk Shared-nothing spawn worker pool, chan/select, timeouts & isolation guards veko run --wasm examples/09_concurrent_worker_pool.vk
examples/10_loopback_tcp_echo_service.vk Loopback TCP server-client, mut buffers & .secret firewall veko run --wasm --allow-net --allow-listen --allow-private-net examples/10_loopback_tcp_echo_service.vk
examples/11_modular_service/src/main.vk Multi-file veko.vk manifest, pub/export, macro + spawn worker pipeline veko run --wasm examples/11_modular_service/src/main.vk
examples/12_typed_structs_and_secrets.vk Typed struct slots, struct/with, secret governance, veko check --strict-types veko run --wasm examples/12_typed_structs_and_secrets.vk
examples/13_pure_vk_tls13_and_codecs.vk Pure-.vk codec/der, codec/pem, codec/http1, X.509 & loopback RFC 8446 TLS 1.3 handshake veko run --native examples/13_pure_vk_tls13_and_codecs.vk
examples/14_http_json_api_server.vk Multi-worker concurrent HTTP/1.1 + JSON REST microservice (spawn store actor + worker pool) veko run --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
examples/15_encrypted_vault_cli.vk Authenticated encrypted file vault (HKDF-SHA256, ChaCha20-Poly1305, Ed25519) veko run --wasm --fuel=0 examples/15_encrypted_vault_cli.vk
examples/16_query_dialect_engine.vk Homoiconic VQL telemetry query & stream dialect (quote, parse-block, macro) veko run examples/16_query_dialect_engine.vk
examples/17_stdlib_cli_fmt_and_collections.vk cli parser, fmt tables/units, testing, math, text, path, seq, coll, rand veko run examples/17_stdlib_cli_fmt_and_collections.vk
examples/18_io_streams_regex_and_codecs.vk buf, io SchemeMux, glob, Thompson NFA regex, dialect, codec/*, compress/deflate veko run examples/18_io_streams_regex_and_codecs.vk
examples/19_modern_crypto_and_sealed_vault.vk SHA3/SHAKE, BLAKE2b, Argon2id, AES-256-GCM, XChaCha20-Poly1305, crypto/seal, ECDSA P-256 veko run --native examples/19_modern_crypto_and_sealed_vault.vk
examples/20_post_quantum_nist_pqc.vk NIST FIPS 203 ML-KEM-768, FIPS 204 ML-DSA-65, and FIPS 205 SLH-DSA-SHAKE-128f veko run --native examples/20_post_quantum_nist_pqc.vk
examples/21_io_streams_dns_and_pqc_tls.vk UUID v7, io/fs, net/dns, and Hybrid Post-Quantum TLS 1.3 (X25519MLKEM768) + HTTP/2 veko run --native examples/21_io_streams_dns_and_pqc_tls.vk
examples/22_web_server_websocket_and_jwt.vk OAuth2 PKCE, HS256/EdDSA/ML-DSA-65 JWTs, web server, and RFC 6455 net/websocket veko run --native examples/22_web_server_websocket_and_jwt.vk
examples/23_zero_ffi_databases_kv_pg_redis.vk Embedded WAL db/kv, PostgreSQL v3 (SCRAM-SHA-256), Redis RESP3, and db/sidecar veko run --native examples/23_zero_ffi_databases_kv_pg_redis.vk
examples/24_signed_vkp_package_bundles.vk Dual-signed Ed25519 + ML-DSA-65 'VKP1' Merkle package bundle creation & verification veko run --native examples/24_signed_vkp_package_bundles.vk
examples/25_batteries_datetime_fs_archives_and_toml.vk datetime, utf8, fs, slog, archive/tar & zip, codec/toml, net/ip, semver, totp veko run examples/25_batteries_datetime_fs_archives_and_toml.vk
examples/26_pure_vk_html_components_and_http_client.vk Auto-escaped html components, template, web/page + gzip, and 3-track net/client veko run --native examples/26_pure_vk_html_components_and_http_client.vk
examples/27_tooling_fmt_lsp_and_v2vk.vk Self-hosted veko fmt, live veko lsp JSON-RPC 2.0 session, and veko v2vk migrator veko run examples/27_tooling_fmt_lsp_and_v2vk.vk
examples/28_simd_optimization_and_arm64_cross_compile.vk f64/sqrt, SIMD bytes/{eq,index-of,xor!,aes-enc-block}, and linux-arm64/macos-arm64 emit veko run --native examples/28_simd_optimization_and_arm64_cross_compile.vk
examples/29_async_reactor_http_server_and_client.vk OS readiness reactor (epoll/kqueue/IOCP), timers, web/serve-reactor, and get-many veko run --native examples/29_async_reactor_http_server_and_client.vk
examples/30_tui_and_native_ui_canvas.vk TrueColor diffing tui, zero-copy RGBA32 ui/canvas & ui/widgets, .ui window, BMP export veko run --native examples/30_tui_and_native_ui_canvas.vk
examples/31_opt_in_ffi_and_c_struct_packing.vk Opt-in .ffi native shared library calls (kernel32.dll / libc.so.6) & C-struct packing veko run --allow-ffi examples/31_opt_in_ffi_and_c_struct_packing.vk
examples/32_durable_objects_and_workflows.vk Transactional durable/object actors, alarms, inboxes, and replay-safe durable/workflow sagas veko run --native examples/32_durable_objects_and_workflows.vk
examples/33_ergonomic_refinements_templates_and_interfaces.vk User /refinements, universal /or [e -> ...], .secret templates, 2-var for, destructuring, and interface veko -A examples/33_ergonomic_refinements_templates_and_interfaces.vk
examples/34_png_charts_and_flex_widgets.vk Light-Mode ui/widgets (stat-card, bar-chart, line-chart, flex/grid) and lossless image/png roundtrip veko examples/34_png_charts_and_flex_widgets.vk
examples/35_sse_multipart_and_kv_queries.vk SSE streaming, multipart/form-data, HTTP 206 Range slices, indexed db/query, and conc/scope veko -A examples/35_sse_multipart_and_kv_queries.vk
examples/36_regex_zstd_otel_and_bindgen.vk Linear-time Thompson NFA text/re, RFC 8878 compress/zstd, and W3C/OTLP/Prometheus otel veko examples/36_regex_zstd_otel_and_bindgen.vk
examples/37_clipboard_x11_flamegraph_and_lock.vk .secret-firewalled clipboard & Hi-DPI, X11 wire-protocol framing, SVG flamegraphs, and veko.lock veko -A examples/37_clipboard_x11_flamegraph_and_lock.vk
examples/hello.vk, examples/tour.vk, examples/oro_closures.vk, examples/dialects.vk Bite-sized introductory tours of syntax, pipes, ORO closures, and block dialects veko run examples/hello.vk
benchmarks/bench_suite.vk Cross-subsystem benchmark suite (math, CRC-32, regex, gzip, SHA3, AES-GCM, ML-KEM) veko run --native benchmarks/bench_suite.vk

2. Basics, Bitwise Ring Buffers & Slicing (01_basics_and_math.vk)

VEKO
title   = 'Veko Basics'
timeout = 250ms
buf-cap = 4kb
proto   = .tcp

head = 12
offset = 7
cap = 16
next-slot = (head + offset) & (cap - 1)   // 3

nums = 1..=5
println (mold nums[1..4])                 // [2 3 4]

3. JSON Filtering, Reduction & match (02_pipelines_and_json.vk)

VEKO
use [j = json, s = strings]

payload = '[{"name": " alpha ", "score": 90, "active": true}, {"name": " beta ", "score": 40, "active": false}, {"name": " gamma ", "score": 85, "active": true}]'

names = payload
    \ j/decode
    \ filter fn [item] [item.active]
    \ map fn [item] [item.name.trim.upper]

println (s/join names ' | ')    // ALPHA | GAMMA

ev = { kind = .ready, code = 200 }
status-msg = match ev.kind [
    .starting ['booting']
    .ready    ['serving']
    _         ['unknown']
]

4. Zero-Alloc Buffers, Secrets, defer, /or & recur (03_oro_buffers_and_errors.vk)

VEKO
use [bytes, ascii, str]

pkt = bytes/with-cap 4kb
bytes/push-all mut pkt (bytes/from-str '  ping trustnode  ')
ascii/trim-right! mut pkt
ascii/upper! mut pkt
bytes/push mut pkt 33
println (str/from-bytes pkt)      //   PING TRUSTNODE!

safe-find = fn [hay needle] [
    defer [println 'cleanup-done']
    str/index-of/or hay needle [-1]
]

5. Homoiconic Dialects & Compile-Time Macros (04_macros_and_dialects.vk)

VEKO
mut endpoints = []
parsed-ok = parse-block (quote [allow .tcp '10.1.0.0/16' 443 allow .udp '10.2.0.0/16' 51820]) [
    any [
        ['allow' proto = enum! cidr = str! p = int!] [
            push mut endpoints (compose [(proto) (cidr) (p)])
        ]
    ]
]

triple = macro [x] [
    compose [(x) + (x) + (x)]
]
println (triple 14)   // 42

6. Capability Records Without OOP (05_closures_and_capabilities.vk)

VEKO
use [str]

make-logger = fn [prefix] [
    {
        info  = fn [msg] [println (str/append prefix msg)]
        warn  = fn [msg] [println (str/append '[WARN] ' msg)]
        flush = fn []    [println (str/append prefix 'flushed')]
    }
]

app-log = make-logger '[veko] '
log-info = app-log.info
(log-info 'initialized')
call app-log.flush

7. Zero-Trust Policy Firewall Compiler (06_policy_firewall_compiler.vk)

Combines homoiconic quote/parse-block rule extraction with a captured ORO map inside make-evaluator to rate-limit, require .mtls, and enforce default-deny verdicts across simulated traffic:

VEKO
policy-spec = quote [
	default .deny
	route .tcp '10.10.' 8443 .mtls 2
	route .udp '192.168.' 51820 .open 5
	route .tcp '0.0.0.' 80 .deny 0
]

ok = parse-block policy-spec [
	any [
		['default' act = enum!] [ default-action = act ]
		['route' p = enum! c = str! pt = int! a = enum! lim = int!] [
			push mut rules (make-rule p c pt a lim)
		]
	]
]

Expected output (veko run examples/06_policy_firewall_compiler.vk):

TEXT
compiled-rules=3
NO_MTLS 10.10.4.20 8443
ALLOW 10.10.4.20 8443
ALLOW 10.10.4.20 8443
LIMIT 10.10.4.20 8443
ALLOW 192.168.1.9 51820
BLOCK 0.0.0.5 80
DENY_DEFAULT 172.16.0.1 9999

8. Binary Wire Frame Codec & In-Place Normalization (07_binary_frame_codec.vk)

Demonstrates big-endian length framing (0x54 0x4e magic, version, opcode, XOR checksum), borrowing mut buffer parameters for zero-copy header/slice reads, in-place ascii/trim-right! + ascii/upper! normalization, and /or fallback on corrupt trailing bytes:

VEKO
decoded = decode-and-normalize/or mut pkt [{ error = 'decode-failed' }]
println (mold decoded)

mut bad-pkt = bytes/with-cap pkt.len
bytes/push-all mut bad-pkt pkt
bytes/push mut bad-pkt 0xff
bad-res = decode-and-normalize/or mut bad-pkt ['recovered-corrupt-frame']
println bad-res

Expected output (veko run examples/07_binary_frame_codec.vk):

TEXT
25
TN
{version = 1, op = 7, payload = '  PING TRUSTNODE'}
recovered-corrupt-frame

9. Single-Owner ORO KV Store & Hash-Chained Audit Log (08_kv_store_and_audit_log.vk)

Encapsulates data, audit, and tip-hash inside one single-owner ORO dispatcher closure (make-kv-store), derives a temporary secret seed inside bytes/with-secret 64b that wipes deterministically on scope return, verifies the hash chain in constant stack via recur, and checks json/encode / json/decode round-tripping:

VEKO
verify-chain = fn [entries idx prev-hash] [
	if idx >= entries.len [return true]
	entry = entries[idx]
	expected = hash (str/join [prev-hash entry.op entry.key] '|')
	if entry.sig != expected [return false]
	recur entries (idx + 1) expected
]

snap = (kv .snapshot .none .none)
encoded = j/encode snap
reloaded = j/decode encoded

Expected output (veko run examples/08_kv_store_and_audit_log.vk):

TEXT
127.0.0.1
8443
audit-valid=true
entries=3
roundtrip-keys=3

10. Shared-Nothing Concurrent Worker Pool (09_concurrent_worker_pool.vk)

Demonstrates structured shared-nothing concurrency across all three backends (vm_oro, backend_wasm, and native_emit.vk) with zero shared mutable heaps or GC pauses: fans jobs out to isolated spawn [ ... ] OS-thread workers over bounded FIFO channels (chan/new, chan/send, chan/recv), multiplexes priority lanes with chan/select, recovers deterministically from slow workers via task/await/timeout/or, and proves that .secret slabs, mut borrows, and closures cannot cross chan/send:

VEKO
w1 = spawn [
	mut processed = 0
	forever [
		item = chan/recv/or fast-q [break]
		chan/send out-q (transform-job item)
		processed = processed + 1
	]
	processed
]

picked = chan/select [lane-a lane-b]
sec-guard = chan/send/or out-q tok ['secret-blocked']

Expected output (veko run --wasm examples/09_concurrent_worker_pool.vk):

TEXT
queue-empty
total-score=116
workers-done=2
selected-lane=1:priority-alert
deadline-exceeded
completed-after-deadline
secret-blocked
mut-loan-blocked
closure-blocked

11. Loopback TCP Service Across Isolated Workers (10_loopback_tcp_echo_service.vk)

Runs a full client/server session over host OS sockets (--vm), wasi:sockets@0.3.0 + wasi:io/async@0.3.0 (--wasm), or WinSock2 / Linux POSIX sockets (--native). Binds an ephemeral local socket (net/listen-tcp .ip '127.0.0.1:0'), spawns a client worker dialing net/connect-tcp, blocks .secret buffer transmission via net/write/or, reads into a pre-allocated ORO mut buffer (net/read-into), normalizes bytes in place (ascii/trim-right!, ascii/upper!), and tears down cleanly:

VEKO
ln = net/listen-tcp .ip '127.0.0.1:0'
client-worker = spawn [
	cli = net/connect-tcp '127.0.0.1' port
	sec-verdict = net/write/or cli api-key 'secret-write-blocked'
	net/write-string cli '  hello veko socket  '
	reply = net/read-bytes cli 64
	net/close cli
	{ sec = sec-verdict, reply = (bytes/to-str reply) }
]

Expected output (veko run --wasm --allow-net --allow-listen --allow-private-net examples/10_loopback_tcp_echo_service.vk):

TEXT
server-rx-bytes=21
client-secret-guard=secret-write-blocked
client-rx=  HELLO VEKO SOCKET

12. Multi-File Modular Service (11_modular_service/)

Combines logical modules and least-privilege veko.vk capability manifests (allow-caps = [.clocks]) with concurrent worker threads: private helpers in lib/protocol stay encapsulated while pub format-telemetry and compile-time alert-threshold execute identically across vm_oro, veko inspect --modules, isolated Wasm worker sandboxes, and --native executables:

VEKO
use [proto = lib/protocol, str]

limit = proto/alert-threshold 80 15
w1 = spawn [
	pkt = proto/format-telemetry 'edge-west-01' 1 'cpu=42%'
	chan/send outbox pkt
	'ok-w1'
]

Expected output (veko run --wasm examples/11_modular_service/src/main.vk):

TEXT
threshold=95
over-limit=true
workers=ok-w1,ok-w2
packets=2
csum-sum=1199
clock-ok=true

13. Typed Structs, .secret Governance & Unboxed Loops (12_typed_structs_and_secrets.vk)

Demonstrates static verification and performance together cleanly under veko check --strict-types, --vm, --wasm, and --native: fixed-schema Upstream and RouteSummary structs with defaults and secret str fields, pure immutable updates via struct/with, os/getenv/secret and bytes/with-secret redaction/JSON-blocking, checked conversions (str/to-i64, as-u8), runtime entry type guards, and an unboxed typed i64 register loop:

VEKO
compute-weight = fn [ep Upstream, factor u8, samples i64] i64 [
	mut acc = 0
	mut i = 0
	while i < samples [
		acc = acc + (i & 7) + factor
		i = i + 1
	]
	acc + ep.port
]

standby = primary \ struct/with { name = 'edge-eu', host = 'eu.veko.local', port = parsed-port }
score = compute-weight standby ok-u8 5000

Expected output (veko check --strict-types examples/12_typed_structs_and_secrets.vk + veko run --wasm examples/12_typed_structs_and_secrets.vk):

TEXT
secret-buf-mold=<secret>
target=edge-eu:eu.veko.local:8443
bad-port=-1
clamped-u8=255
summary={"name":"edge-eu","host":"eu.veko.local","port":8443,"load":85943}

14. Pure-Veko DER/PEM/HTTP Codecs, X.509 & Loopback TLS 1.3 (13_pure_vk_tls13_and_codecs.vk)

Demonstrates Veko's 100% pure-.vk protocol and cryptographic stack (codec/der with parse-block AST nodes, codec/pem, codec/http1, crypto/sha256, crypto/x25519 Ed25519, crypto/x509 SPKI pinning, and net/tls13) executing an in-process loopback RFC 8446 TLS 1.3 + HTTP/1.1 exchange with zero OS crypto DLLs:

POWERSHELL
veko run --allow-net --allow-listen --allow-private-net examples/13_pure_vk_tls13_and_codecs.vk
veko run --wasm --fuel=0 --allow-net --allow-listen --allow-private-net examples/13_pure_vk_tls13_and_codecs.vk
veko compile --native examples/13_pure_vk_tls13_and_codecs.vk -o dist/13.exe ; ./dist/13.exe

15. Concurrent HTTP/1.1 + JSON REST Microservice (14_http_json_api_server.vk)

Demonstrates a multi-worker concurrent HTTP/1.1 + JSON REST microservice across all three backends using typed structs (TaskItem, ApiMetrics + struct/with), a channel-owned spawn store actor, a 2-worker spawn pool with reusable per-worker reply_ch, net/listen-tcp .ip '127.0.0.1:0', codec/http1, parse-block (http/request-to-block ...), json/decode/or + json/encode/or, time/now/time/since, and .secret JSON firewall enforcement:

VEKO
req_blk_ok = parse-block (http/request-to-block sample_req) [
    any [
        [.req m = str! t = str! _v = str! _h = map! _b = any!] [
            parsed_method = m
            parsed_target = t
        ]
    ]
]

Run across all three backends (veko check -> 2 module(s), 2 struct(s), 22 typed fn(s)):

POWERSHELL
veko check examples/14_http_json_api_server.vk
veko run --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
veko compile --vko examples/14_http_json_api_server.vk -o dist/14.vko ; veko run --allow-net --allow-listen --allow-private-net dist/14.vko
veko run --wasm --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
veko compile --native examples/14_http_json_api_server.vk -o dist/14.exe ; ./dist/14.exe

Expected output (identical 10 lines across --vm, .vko, --wasm, and --native):

TEXT
secret-firewall=secret-json-blocked
req-block-parsed=true:POST:/items
health=200:'ok'
created-ids=1,2|statuses=201,201
malformed-json=400:'invalid_json'
list-count=2
done-item1=200:done=true
missing-item=404:'not_found'
metrics=handled:8,created:2,workers:2
pool=accepted:8,served:8,actor:8,timing-ok=true

16. Authenticated Encrypted File Vault CLI (15_encrypted_vault_cli.vk)

Implements an authenticated encrypted file vault and Ed25519-signed multi-block PEM manifest CLI using HKDF-SHA256, ChaCha20-Poly1305 AEAD, HMAC-SHA256 + ct-eq, Ed25519, codec/pem + parse-block, bytes/with-secret, os/getenv/secret, and os/args. Invoking with zero arguments runs an in-process self-demo (including Ed25519 tamper, AEAD tamper, wrong-passphrase, and .secret firewall tests) and scrubs the temporary demo file; passing arguments invokes the init, set, get, list, verify, or --help CLI subcommands with --pass <pw>.

Run across all three backends (veko check -> 5 module(s), 2 struct(s), 84 typed fn(s)):

POWERSHELL
veko check examples/15_encrypted_vault_cli.vk
veko run examples/15_encrypted_vault_cli.vk
veko run --wasm --fuel=0 examples/15_encrypted_vault_cli.vk
veko compile --native examples/15_encrypted_vault_cli.vk -o dist/15.exe ; ./dist/15.exe

# Interactive CLI subcommands (pass --allow-fs on --wasm)
veko run examples/15_encrypted_vault_cli.vk -- init vault.pem --pass mypw
veko run --wasm --allow-fs --fuel=0 examples/15_encrypted_vault_cli.vk -- init vault.pem --pass mypw

Expected self-demo output:

TEXT
vault-secret-mold=<secret>|name=master
vault-secret-firewall=secret-json-blocked
vault-sealed=exists:true,entries:3,cipher:chacha20-poly1305
vault-ed25519-verify=true
vault-unseal=api:tok_prod_veko_991,db:postgres://vault.local/app,tls:sha256/veko-spki-pin
tamper-ed25519-rejected=true
tamper-aead-rejected=true
wrong-pass-rejected=true
demo-scrubbed=true

17. Homoiconic VQL Telemetry Query & Dialect Engine (16_query_dialect_engine.vk)

Combines homoiconic quote, parse-block AST compilation, compile-time macros (sla-budget, sla-floor), compose/deep, typed structs (TraceSpan, QueryPlan + struct/with), filter/map/reduce, match, tail-recursive recur, str/to-i64/or, as-u8/or, and an optional os/args[0] latency threshold override:

POWERSHELL
veko check examples/16_query_dialect_engine.vk
veko run examples/16_query_dialect_engine.vk
veko compile --vko examples/16_query_dialect_engine.vk -o dist/16.vko ; veko run dist/16.vko
veko run --wasm examples/16_query_dialect_engine.vk
veko compile --native examples/16_query_dialect_engine.vk -o dist/16.exe ; ./dist/16.exe
./dist/16.exe 200

Expected output:

TEXT
vql-parsed=true|name=edge-5xx-slow|clauses=3
vql-matched=3|limited=2|sum-bytes=7520
vql-rows=1:edge-gateway@eu-west:502:145ms,4:edge-gateway@eu-west:504:320ms
macro-plan={"name":"sla-watchdog","svc":"edge-gateway","min_ms":100,"status_min":500,"region":"eu-west","limit":5,"agg":"sum_bytes"}
sla-budget=240|breaches=2|max-ms=320|clamped-u8=255
report-ast=[vql 'edge-5xx-slow' [parsed true matched 3 returned 2 sum_bytes 7520] sla [plan 'sla-watchdog' budget_ms 240 breaches 2 max_ms 320]]

17b. Systems, Networking, Async Reactor, UI/FFI & Durable Workflow Examples (21..32)

Twelve end-to-end systems examples exercise Veko 1.0's connected networking, web/auth, zero-FFI databases, signed packages, developer tooling, hardware SIMD & ARM64 cross-compilation, readiness reactor, TUI/native UI, opt-in FFI, and durable workflows:

  • examples/21_io_streams_dns_and_pqc_tls.vk: Time-ordered UUID v7, positioned io/fs streams, net/dns resolution, and a live loopback Hybrid Post-Quantum TLS 1.3 (X25519MLKEM768) + ALPN 'h2' + net/http2 RPC.
  • examples/22_web_server_websocket_and_jwt.vk: OAuth 2.0 PKCE S256, HS256/EdDSA/ML-DSA-65 JWTs, web routes with security headers/SSE, and live RFC 6455 net/websocket upgrade + masked frames.
  • examples/23_zero_ffi_databases_kv_pg_redis.vk: Embedded WAL KV store (db/kv + AES-256-GCM put-sealed), loopback PostgreSQL v3 (SCRAM-SHA-256), pipelined Redis RESP3 (db/redis), and 'VKSC' db/sidecar frames.
  • examples/24_signed_vkp_package_bundles.vk: Packs and verifies a multi-module 'VKP1' archive dual-signed with Ed25519 + ML-DSA-65 (pkg/vkp).
  • examples/25_batteries_datetime_fs_archives_and_toml.vk: Exercises datetime, utf8, fs, slog, archive/tar (.tar.gz), archive/zip, codec/toml, net/ip, semver, auth/totp, diff, and retry.
  • examples/26_pure_vk_html_components_and_http_client.vk: Auto-escaped lib/html components, lib/template, web/page + gzip, and loopback requests via net/client.
  • examples/27_tooling_fmt_lsp_and_v2vk.vk: Exercises veko fmt, a live veko lsp JSON-RPC 2.0 session, and veko v2vk source migration.
  • examples/28_simd_optimization_and_arm64_cross_compile.vk: Exercises hardware f64/sqrt, SIMD bytes/{eq,index-of,xor,xor!,aes-enc-block}, and cross-compiles standalone linux-arm64 ELF64 and macos-arm64 Mach-O binaries.
  • examples/29_async_reactor_http_server_and_client.vk: Exercises lib/reactor.vk (epoll/kqueue/IOCP+WSAPoll), monotonic timers, cross-thread wakeups, web/serve-reactor, and concurrent net/client/request-batch.
  • examples/30_tui_and_native_ui_canvas.vk: Exercises double-buffered TrueColor lib/tui.vk, zero-copy RGBA32 lib/ui/canvas.vk + lib/ui/widgets.vk, .ui window presentation, and 24-bit BMP export.
  • examples/31_opt_in_ffi_and_c_struct_packing.vk: Demonstrates opt-in --allow-ffi dynamic shared library calls (kernel32.dll / libc.so.6) and deterministic little-endian C-struct packing (lib/ffi.vk).
  • examples/32_durable_objects_and_workflows.vk: Exercises crash-safe durable/object actor turns, alarms, and FIFO inboxes alongside replay-safe durable/workflow steps, retries, signals, and LIFO sagas over db/kv.
  • examples/38_zero_ffi_sqlite_and_orm.vk: Exercises genuine "SQLite format 3\0" 4096-byte slotted B-tree pages, CREATE UNIQUE INDEX, BEGIN/ROLLBACK, SQL aggregates, and the homoiconic ORM (db/sqlite) across --vm, --wasm --check-slabs, and --native.
  • examples/39_debugger_coverage_and_fuzzing.vk: Exercises testing/fuzz (fuzz-bytes, fuzz-block) with automatic delta-debugging counterexample shrinking alongside veko test --coverage and veko debug.
  • examples/40_sdk_https_registry_and_wayland.vk: Exercises veko-lang.org + decentralized HTTPS .vkp registry resolution (pkg/lock), VEKO_LIB .ffi search paths, and Linux Wayland (wl_shm + xdg_wm_base) wire framing (ui/wayland).

17c. Multi-Module Showcase Applications (demos/)

Beyond single-file examples, demos/ provides six complete multi-module applications demonstrating full-stack architecture across --vm, --wasm, and --native:

Application Modules What It Demonstrates
demos/widget_gallery/ model.vk, pages.vk, main.vk 29-widget Light-Mode desktop UI gallery (ui/widgets, ui/layout, ui/font, image/png, ui), clipboard selection (Ctrl+A/Ctrl+C/Ctrl+V), Per-Monitor V2 Hi-DPI badge, live desktop mode (-- --live), and lossless PNG export.
demos/taskflow_studio/ auth.vk, store.vk, ui_assets.vk, main.vk Role-separated Light/Dark web portal & admin console (/ui/auth, /ui/portal, /ui/admin), HS256 JWT + TOTP 2FA, durable/object customer wallets, durable/workflow order fulfillment + LIFO sagas, and live web/serve-reactor mode (-- --serve 8095).
demos/canvas_workbench/ state.vk, views.vk, main.vk 720x440 immediate-mode desktop GUI (ui/canvas, ui/widgets, ui) with 4 tabs (Topology, Sketch Pad, Durable db/kv Sprint Board, SHA-256 Frame Profiler), Light/Dark toggle, live 60 FPS -- --live / --gui window mode, and BMP export.
demos/pulse_mesh/ wire_frame.vk, mesh_broker.vk, tui_inspector.vk, main.vk Multi-protocol broker combining 'VKPM' binary frames (codec/wire + deflate + crc32 + Ed25519 tickets), TCP pub/sub, UDP gossip heartbeats, RFC 6455 WebSocket frames, HTTP upstream probes, homoiconic parse-block routes, and TrueColor tui inspector.
demos/vault_dialect/ policy.vk, vault_core.vk, main.vk Structured cli flags, homoiconic parse-block RBAC dialect, NIST ML-KEM-768 + ML-DSA-65, and AES-256-GCM db/kv/put-sealed scoped zeroization.
demos/netpulse_tui/ main.vk Compact health-probe monitor combining web/serve-async, net/client/get-many, tui, and a 320x160 RGBA32 ui/canvas telemetry card.

18. Three-Backend Parity & Self-Hosting Convergence (S1 == S2)

The unified 46-module pure-Veko single-binary SDK in src/ (embedding all 93 lib/ standard library modules via src/stdlib_vfs.bin) compiles itself across Windows x86_64 (dist/bin/veko.exe PE32+), Windows 11 ARM64 (--target=win-arm64 PE32+ 0xAA64), Linux x86_64 (dist/bin/veko static ELF64), Linux AArch64 (--target=linux-arm64 static ELF64), macOS Apple Silicon (--target=macos-arm64 signed 16 KiB Mach-O), Wasm 3.0 (veko.wasm), and 64-bit VKO bytecode (veko.vko), proving byte-for-byte S1 == S2 native fixed-point convergence across x86_64 and AArch64.


Part XIII: Administrator & Security Governance Guide

Operational guidance for building, verifying, configuring, and governing Veko 1.0 workloads across local 64-bit VKO VM deployments (oro_vm.vk), vvm WebAssembly 3.0 zero-trust sandboxes (codegen.vk), and standalone native executables (native_emit.vk & arm64_emit.vk across win-x64, win-arm64, linux-x64, linux-arm64, and macos-arm64).

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

1. Build & Verification Pipeline

Veko ships with a pure-.vk build orchestrator (build.vk) that enforces static checks, multi-suite verification, documentation hygiene, and S1 == S2 self-hosting convergence:

Command / Target Action Purpose
check (veko run build.vk -- check) Static DAG check Validates all 76 compiler/runtime modules (src/main.vk) and strict-typed examples
test (veko run tests/run_tests.vk) Runs 18 test suites Validates lexer, Pratt parser, types/secrets, 64-bit VKO, stdlib, PQC, TLS 1.3, reactor, durable workflows, UI/X11/clipboard/FFI, flamegraphs, veko.lock, and 3-track parity
docs (veko docs) Compiles dist/docs/ Renders isolated End-User and Technical HTML suites + interactive SVG diagrams + hygiene checks
build (veko run build.vk -- build) Builds binary + docs Refreshes HTML docs and compiles a 2-stage S1 == S2 native veko binary into dist/bin/
fixed-point Fixed-point gate Verifies byte-for-byte S1 == S2 convergence for native machine code and 64-bit VKO
all (veko run build.vk -- all) Full release gate Runs check, test, docs, and build sequentially

2. Three-Backend Operational Profiles

Operators select among Veko's three execution tracks depending on trust boundary, portability, and deployment target:

  • Track A — 64-Bit VKO Bytecode VM (oro_vm.vk / --vm / .vko): Fast local tooling, interactive veko repl, doctests, dynamic eval, and precompiled 64-bit VKO execution with runtime --allow-* capability flags.
  • Track B — WebAssembly 3.0 Sandbox (codegen.vk / --wasm / vvm): Zero-trust execution for untrusted plugins and multi-tenant workloads inside vvm's HostSandbox, enforcing --fuel, --mem-pages, --allow-fs=<dir>, --allow-hosts, SSRF blocking, and strict .ffi prohibition.
  • Track C — Native x86_64 & AArch64 (native_emit.vk + arm64_emit.vk / --native): Standalone Windows PE32+ (--target=win-x64 & --target=win-arm64 0xAA64, optional --gui), static zero-libc Linux ELF64 (--target=linux-x64 & --target=linux-arm64), and ad-hoc SHA-256 signed 16 KiB Apple Silicon Mach-O (--target=macos-arm64) binaries with CPUID AVX2/SSE2/AES-NI, OS-native readiness reactors (epoll/kqueue/IOCP), and opt-in .ffi shared library trampolines.
Operational Dimension Track A: 64-Bit VKO VM (--vm) Track B: vvm Wasm 3.0 (--wasm) Track C: Native x86_64 & ARM64 (--native)
Trust Boundary Trusted local CLI scripts, tools, and interactive REPL Untrusted plugins, multi-tenant edge rules, and sandboxed tasks Trusted standalone OS executables (zero external compiler, JVM, or GC)
Host Interface Guarded VmPolicy OS PAL (fs, net, reactor, offscreen ui) WASI 0.3 + explicit HostSandbox capability allowlists (.ffi forbidden) Win32 IAT (win-x64/win-arm64), direct Linux syscalls (linux-x64/linux-arm64), or libSystem (macos-arm64)
Resource Metering --fuel=<n> instruction quota + VmPolicy sleep/output caps + deterministic ORO cleanup vvm --fuel budget + --mem-pages ceiling + --check-slabs leak gate Thread-local 12-bucket ORO slab free-lists + deterministic .secret zero-wipe
Supply Chain Verifies veko.vk trust-keys on .vkp bundles Verifies veko.vk trust-keys on .vkp bundles Verifies veko.vk trust-keys + emits SHA-256 LC_CODE_SIGNATURE on macos-arm64

3. Security, Capability & Secret Governance

Project Manifest Confinement (veko.vk)

Across all three backends, operators enforce static build-time confinement via veko.vk:

  • Canonical Path Confinement: Project root and every resolved .vk/.vko module path are verified via canonical real-path containment so symlink and ../ escapes are rejected before parsing.
  • Least-Privilege Capability Allowlisting (allow-caps):
    • .fs — Filesystem access (os/read-*, os/write-*, os/open, os/pread, os/pwrite, os/stat, etc.)
    • .clocks — Wall/monotonic clocks and sleeps (time/*)
    • .env — Environment variables and CLI args (os/getenv, os/args)
    • .net — TCP/UDP sockets, DNS, HTTP, and readiness reactor (net/*, http/*)
    • .exec — Child process execution (os/exec)
    • .ui — Native window surfaces (ui/*; Win32 user32.dll/gdi32.dll imported only when used)
    • .ffi — Foreign C-ABI shared libraries (ffi/*; denied by default unless allow-caps = [.ffi] or --allow-ffi is set; strictly forbidden on --wasm)
  • Signed 'VKP1' Package Pinning (trust-keys): Pinning trust-keys = ['ed25519:<hex>', 'mldsa65:<hex>'] inside veko.vk ensures every .vkp dependency is Merkle-verified against trusted publisher keys before loading.

Sensitive Buffer Zeroization & .secret Firewall

Unlike garbage-collected runtimes where keys linger in uncollected heap pages:

  • No SSO Escape + Volatile Zero-Wipe: Values from os/getenv/secret and bytes/with-secret always allocate flag_secret heap slabs whose full capacity is overwritten with zeroes before returning to any free-list.
  • Automatic Redaction: print, println, mold, and log/* redact .secret values to <secret>.
  • Compile-Time & Runtime Sink Blocking: Deep taint checks block .secret values from crossing net/*, http/*, spawn, chan/send, json/encode, os/write-file, ui/present, and ffi/*.

4. Troubleshooting & Diagnostics

Symptom Likely Cause Operator Resolution
unknown word 'n-1' Missing spaces around subtraction operator - Add spaces (n - 1); Veko treats n-1 as a kebab-case word
capability error: ... requires .ffi Foreign library call without explicit FFI opt-in Pass --allow-ffi or declare allow-caps = [.ffi] in veko.vk (native/VM only)
docgen hygiene: decorative Unicode emoji Emoji character introduced into Markdown or HTML docs Replace with plain text or inline vector SVG icon
docgen hygiene: forbidden source ext Non-Veko source filename leaked into docs Refer to pure-Veko modules (lexer.vk, parser.vk, oro_vm.vk, codegen.vk, native_emit.vk)
veko inspect unexpected precedence Missing (...) around compound math passed to prefix word Wrap compound inline expressions as (offset + 4)

Part XIV: CLI, Build & Syntax Reference

Complete reference for Veko CLI commands, build script targets, lexical tokens, numeric literals, Pratt operator precedence, and builtin arities.


1. CLI Commands

Command Status Description
veko <file.vk|file.vko|dir|.> [-- args...] Active Zero-flag workspace or script shorthand (auto-honors veko.vk allow-caps)
veko init [dir] [--cli|--web|--gui|--lib|--pkg|--strict|--agents|--ci|--sync] Active Scaffold veko.vk + AGENTS.md, generate CI/Dockerfile (--ci), scaffold a .vkp package (--pkg), or sync allow-caps (--sync)
veko doctor [--offline] [dir] Active Audit toolchain tracks, embedded 95-module VKFS, VEKO_HOME / ~/.veko_modules, veko.vk & AGENTS.md, and registry reachability
veko debug [--dap|-b <[file:]line>|--script=<s>] [file.vk] Active Launch the interactive source debugger (s, n, f, c, bt, locals, p, <secret> redacted) or VS Code F5 DAP server
veko test [--coverage[=<html]>|--lcov=<info>] [--vm|--wasm|--native] [file|dir]... Active Discover and execute *_test.vk suites, --doctests, and Light-Mode HTML / LCOV line coverage reports
veko bench [--save=<json>|--compare=<json>] [--runs=<n>] [--flamegraph[=<svg>]] [file|dir]... Active Run *_bench.vk micro-benchmarks, save JSON baselines, diff regressions (FASTER/SLOWER), and emit SVG flamegraphs
veko check [--strict-types] [--no-cache] [-A|-C <csv>|--allow-ffi] [file|dir] Active Run gradual or strict type checking, exhaustive match & fallible /or checks, interface contracts, mut loans, capability auditing, and .secret taint verification
veko run [--vm|--wasm|--native] [--fuel=<n>] [--profile[=<svg>]|--flamegraph[=<svg>]] [--watch] [-e <code>] [-A|-C <csv>] [file|dir] Active Execute on 64-bit VKO VM (with optional --fuel quota, call-frame profiling & SVG flamegraph), Wasm 3.0 (vvm), or host-auto-detected cached AOT native
veko build|compile [--native|--wasm|--vko] [--target=<t>] [--gui] [--no-cache] [file|dir] [-o out] Active Tree-shaken compilation to native (win-x64, win-arm64, linux-x64, linux-arm64, macos-arm64), Wasm 3.0, or 64-bit VKO (with content-addressed mod_v1 cache)
veko repl Active Launch the interactive 64-bit VKO VM REPL (:help, :stats, :reset, :quit)
veko doc [--html [--dir <d>]|--test|--json|--md] [-o out] [mod|file...] Active Emit self-contained HTML API docs (with live Wasm 3.0 doctests & <canvas> previews), multi-page --dir, api.json, Markdown, or run doctests
veko docs [out_dir] Active Render End-User and Technical HTML documentation suites (default dist/docs) and enforce hygiene checks
veko book [--cookbook|--html|--all] [out] Active Compile Programming in Veko and The Veko Cookbook as single-page-cover EPUB 3.0 ebooks and full searchable multi-chapter HTML books
veko bindgen <header_path> [-l <lib>] [-o <out.vk>] Active Parse C ABI declarations and generate idiomatic Veko .ffi struct packers and function wrappers
veko fmt [--check|--write|-w|--diff] <file.vk|dir>... Active Format Veko source files canonically while preserving load-bearing [tight]/[spaced] tokens, strings, and comments
veko lsp Active Start the native JSON-RPC 2.0 Language Server (diagnostics, hover, definition, completion, document symbols, formatting, quick-fixes)
veko go2vk|py2vk|rs2vk|v2vk <input> [-o out.vk] Active Translate Go, Python, Rust, or V source into formatted Veko starter files with automatic stdlib/dependency mapping and TODO markers
veko migrate [--from=go|py|rust|v] <input> [-o out.vk] Active Unified migration driver (auto-detects language from file extension or explicit --from=)
veko pkg <search|info|add|list|keygen|pack|index|verify|inspect|lock|fetch|verify-lock> Active Search/inspect/install veko-lang.org .vkp packages, generate Ed25519 publisher keys, pack signed bundles, and build static HTTPS registry indexes
veko inspect --tokens <file.vk> Active Dump whitespace-aware lexer tokens (line:col and [tight]/[spaced] flags)
veko inspect --ast <file.vk> Active Dump the resolved two-pass Pratt AST and preserved RawBlocks
veko inspect --bytecode <file.vk> Active Disassemble compiled 64-bit VKO bytecode functions and constants
veko inspect --modules <file.vk> Active Audit the resolved dependency DAG, module file paths, exported symbols, and capability usage
veko inspect --vko <file.vko> Active Inspect 64-bit .vko header capabilities, exports, and disassembled VKO bytecode
veko inspect --wasm <file.vk> Active Compile to Wasm 3.0 and inspect module functions, globals, memory, and size
veko version / veko help Active Print toolchain version, backend summary, and command reference

1a. Top-Level Compile Shorthands & Cross-Hosted Execution (src/main.vk)

The unified pure-Veko veko CLI (src/main.vk, 77 compiler modules + 95 embedded stdlib modules via 'VFS2' stdlib_vfs.vk) executes on Track A (.vko inside oro_vm.vk), Track B (.wasm inside vvm / WASI), and Track C (dist/bin/veko.exe win-x64 PE32+, win-arm64 PE32+ 0xAA64, dist/bin/veko static Linux ELF64, linux-arm64 static ELF64, or macos-arm64 Mach-O), accepting top-level compile flags (veko --native ..., veko --wasm ..., veko --vko ...) as shorthands for veko compile:

Invocation Description
veko [--native|--wasm|--vko] [--target=<win-x64|win-arm64|linux-x64|linux-arm64|macos-arm64>] [--gui] <entry.vk> [-o <out>] Shorthand compile of a single file or modular DAG to any of the 5 native targets, WebAssembly 3.0 (.wasm), or 64-bit VKO bytecode (.vko)
veko compile --native --target=win-arm64 <entry.vk> -o out.exe Cross-compile a standalone Windows 11 ARM64 PE32+ (0xAA64) executable from any host OS
veko compile --native --target=linux-arm64 <entry.vk> -o out Cross-compile a static zero-libc Linux AArch64 ELF64 binary from any host OS
veko compile --native --target=macos-arm64 <entry.vk> -o out Cross-compile a 16 KiB ad-hoc SHA-256 signed Apple Silicon Mach-O executable
veko run --native <entry.vk> [-- args...] Compile once to dist/.veko_cache/<sha256> and execute at full native machine speed

1b. Project Manifest (veko.vk) & Module Visibility

Place an optional homoiconic veko.vk manifest in your project directory to configure roots, dependencies, and capability limits:

VEKO
{
  name       = 'edge-service'
  root       = 'src'
  deps       = { auth = '../shared-auth', stats = 'vendor/stats.vkp' }
  allow-caps = [.fs .clocks .env .net]
  trust-keys = ['ed25519:a1b2c3...']
}
  • pub & export: Modules are private by default; functions, macros, and struct schemas may be exported (pub Endpoint = struct { ... }, pub encode = fn [x] [...], or export [Endpoint encode decode-macro]). Mutable module globals cannot be exported.
  • Logical use Paths: Import sibling, stdlib, or dependency modules cleanly (use [c = lib/codec, auth]); OS paths and .vk suffixes are forbidden in source imports.
  • Capability Audit: When allow-caps is present, .fs, .clocks, .env, .net, .exec, .ui, and default-deny .ffi usage is verified transitively across the dependency graph before execution.
  • Signed 'VKP1' Bundle Trust (trust-keys): Any deps entry ending in .vkp is cryptographically verified (SHA-256 Merkle root + Ed25519 and/or ML-DSA-65 signature) against trust-keys before module loading.

1c. Execution Backends Reference & Decision Matrix

Backend Purpose & Intended Workload Runtime Mechanics Notes
Track A: oro_vm.vk (--vm / .vko) Instant script execution, veko repl, doctests, dynamic eval, and .vko distribution Fixed-width 64-bit VKO bytecode VM (op:u8 | flags:u8 | a:u16 | bx:u32) + zero-W^X superinstructions + VmPolicy PAL Supports runtime eval, gensym, and host http/fetch
Track B: codegen.vk (--wasm / vvm) Zero-trust capability-confined plugins, fuel/memory quotas, and slab leak verification Validated Wasm 3.0 (try_table, return_call, bulk memory, 12-bucket ORO RAM) in vvm HostSandbox + --check-slabs .ffi is strictly forbidden to preserve sandbox isolation
Track C: native_emit.vk + arm64_emit.vk (--native) Standalone win-x64 & win-arm64 (0xAA64) PE32+ (--gui), linux-x64 & linux-arm64 static ELF64, and macos-arm64 Mach-O binaries Direct x86_64 (AVX2/SSE2/AES-NI) & AArch64 codegen, 79-group DCE, 12-bucket ORO slab free-lists, OS readiness reactors (epoll/kqueue/IOCP), DNS/TLS 1.3, .ui, and opt-in .ffi Omits dynamic string eval; use net/client + web for cross-track HTTP

2. Build Orchestrator Targets (build.vk)

Target Invocation Description
all (default) veko run build.vk -- all Run check, test, docs, and 2-stage S1 == S2 native fixed-point dist/bin/veko build
check veko run build.vk -- check Verify all 77 compiler modules (src/main.vk) and strict-typed examples
test veko run tests/run_tests.vk Run all 18 pure-.vk automated verification suites
docs veko docs Render dist/docs/user/ & dist/docs/technical/ + run hygiene gate
build veko run build.vk -- build Render HTML docs and verify 2-stage native S1 == S2 fixed-point dist/bin/veko
fixed-point veko run build.vk -- fixed-point Verify native machine code and 64-bit VKO bytecode fixed points
help veko run build.vk -- help Print build orchestrator help

3. Rich Literal Reference

Category Examples Internal Representation
Integers 42, -5, 0xff, 0b1010, 1_000 Signed i64
Floats 3.14, 0.25 IEEE-754 f64
Durations 100ns, 50us, 250ms, 5s, 2m, 1h i64 nanoseconds
Byte Sizes (1024-based) 64b, 4kb (4096), 16mb, 1gb, 4kib, 16mib, 1gib i64 bytes (1024^n)
Strings 'hello\n', 'C:\\path' UTF-8 (\n, \r, \t, \\, \', \0)
Enums / Symbols .tcp, .ip, .denied (must be spaced/after opener) Interned enum_lit

4. Pratt Operator Precedence Table

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
Binding Power Category Operators / Forms Notes
80 Postfix (tight) x.field, s.trim, table[i], buf[0..n] Requires tight == true (no leading whitespace)
70 Prefix & Unary -x, not x, word arg1 ... argN, mut x Binds tighter than arithmetic and comparisons
60 Multiplicative / Shift / Mask *, /, %, <<, >>, >>>, & Spaced / is divide; tight / is path; >>> is logical unsigned shift
50 Additive / Bitwise +, -, ^, | Spaced - is subtract; tight - is kebab-case
40 Range .., ..= Half-open or inclusive range
30 Comparison ==, !=, <, <=, >, >= Terminates prefix word arguments cleanly
20 Logical and, or Short-circuiting boolean logic
10 Pipe lhs \ word arg2 ... argN Injects lhs as first argument; spans newlines
0 Statements & Control =, def, use, if, unless, while, forever, defer, with, match, return Top-level and block statements

5. Builtin Word Arities & Backend Coverage

Word / Path Base Arity Backend Coverage Notes
print, println, len, empty?, zero?, even?, odd?, not, hash, abs, pop, first, last, mold, err, err?, ok?, type-of, call, compose, compose/deep 1 All 3 Single-argument words across oro_vm.vk, codegen.vk, and --native
eval 1 VM only Dynamic runtime evaluation (oro_vm.vk only)
gensym 1 VM + Wasm Unique symbol generation (oro_vm.vk + codegen.vk)
min, max, add, sub, filter, map, each, push, parse-block 2 All 3 Two-argument words (\ pipe supplies arg 1)
put, reduce, map/set, block/set, bytes/set, bytes/set-{u16,u32,i64}-{le,be} 3 All 3 O(1) in-place or CoW update (put mut obj .field val / put mut xs idx val)
map/keys, block/with-cap, bytes/zeroize!, os/exists?, os/real-path, os/stat, os/read-dir, os/mkdir, os/remove, os/close, os/fsync, net/resolve 1 All 3 Core map, slab, filesystem, and DNS resolution builtins
map/get, map/has?, map/delete, str/contains?, str/byte-at, bytes/fill, bytes/{get,push}-{u16,u32,i64}-{le,be}, os/open, os/rename, os/truncate, os/exec 2 All 3 Add +1 per /refinement (/or [fallback]); os/exec requires .exec
os/pread, os/pwrite 3 All 3 (fd, buf_or_len, offset) positioned crash-safe file I/O (.fs gated)
str/trim, str/upper, str/lower, str/from-bytes, str/to-i64, str/to-f64, as-u8, as-i64, as-f64, bytes/with-cap, bytes/with-secret, random/bytes, json/decode, json/encode, os/getenv, os/getenv/secret, os/read-file, net/accept, net/addr, net/close 1 All 3 Add +1 per /refinement (e.g. /or [fallback])
str/append, str/join, str/split, str/index-of, struct/with, bytes/push, bytes/push-all, bytes/append, bytes/copy-into, os/write-file, net/listen-tcp, net/connect-tcp, net/read-bytes, net/read-into, net/write, net/write-string, net/udp-bind, net/udp-recv-from, chan/send, json/get 2 All 3 Add +1 per /refinement (/timeout, /nonblock, /backlog, /or)
net/udp-send-to 4 All 3 (sock, host, port, payload) UDP datagram transmit (.net gated)
net/http/fetch, http/fetch (1); http/request, net/http/request (3) 1 / 3 VM + Wasm Host HTTP helpers; for 3-backend HTTP use pure-.vk net/client and web
chan/new, chan/recv, chan/try-recv, chan/close, chan/select, task/await 1 All 3 Add +1 for /timeout and +1 for /or
spawn 1 All 3 Control block spawning an isolated worker returning a task ID
f64/sqrt 1 All 3 Hardware IEEE-754 square root (SQRTSD / FSQRT / f64.sqrt)
bytes/eq, bytes/index-of, bytes/xor, bytes/xor!, bytes/aes-enc-block 2 All 3 Bulk SIMD / hardware-accelerated (AVX2/SSE2/AES-NI on x86_64)
net/poll-new (0), net/poll-wake/poll-close/sock-error/try-accept (1), net/poll-wait/set-nonblock/connect-tcp/nonblock/try-write (2), net/try-read-into (3), net/poll-ctl (5) 0..5 All 3 OS-native readiness reactor PAL (epoll / kqueue / IOCP+WSAPoll / WASI net-poll); .net gated
ui/open (3), ui/poll-events (1), ui/present (4), ui/close (1), ui/clipboard-get (0), ui/clipboard-get/secret (0), ui/clipboard-set (1), ui/dpi-scale (1) 0..4 All 3 Curated .ui window, clipboard (.secret-firewalled), and Hi-DPI PAL (lib/ui.vk wrapper recommended)
ffi/open (1), ffi/sym (2), ffi/call (2), ffi/close (1) 1..2 Native + VM Opt-in .ffi C-ABI foreign library PAL (lib/ffi.vk); forbidden on --wasm
time/now, time/unix, os/args, os/cwd, os/temp-dir 0 All 3 Zero-argument clock and process environment reads

6. Coding-Agent & LLM Language Quick Reference (Constructs & Pitfalls)

Because Veko uses fixed-arity prefix words with spaced infix arithmetic instead of C/Python function parentheses, review these five rules and canonical patterns before writing .vk modules (see also the root AGENTS.md file):

Core Grammar Rules

  1. No Call Parentheses or Commas: Call words left-to-right (os/write-file path data). Use (...) only to group nested subexpressions inside math or arguments (while i < (len hkeys) [ ... ], bytes/with-cap ((len head_b) + blen)).
  2. Spaced Binary - and /: Write n - 1 and a / b with spaces; n-1 is a single kebab-case word and a/b is a module/refinement path.
  3. Tight .field and [i]; Spaced .enum: Field chains and indices allow no space before . or [ (peer.host, raw.trim.upper, buf[0..n]); standalone enum tags require leading space or an opener (mode = .tls, return .ok).
  4. Delimiters: [ ... ] wraps code blocks, parameter lists, data lists, and slices; { ... } wraps struct definitions, struct literals, and maps; '...' wraps UTF-8 strings; // starts comments.
  5. Two-Sided mut: Mark mutable bindings with mut and annotate in-place parameter mutations on both signature (fn [mut buf bytes]) and call site (append-nl mut pkt).

Construct Examples at a Glance

VEKO
use [h = net/http, j = json]

pub Endpoint = struct { host str, port i64 = 443, key secret str = '' }
pub build-ep = fn [host str] Endpoint [
    ep = Endpoint { host = host }
    ep \ struct/with { port = 8443 }
]

fetch-safe = fn [url str] [
    defer [ print 'cleanup' ]
    raw = h/fetch/timeout/or url 3s [ return (err 'fetch timeout') ]
    raw \ j/decode
]

ch = chan/new 4
t = spawn [
    chan/send ch 'ok'
    1
]
status = chan/recv/or ch [ 'closed' ]
code = task/await t

Habit-Correction Table (From C / Python / Go / Rust)

Common Habit Avoid Use in Veko
Call parens len(xs), min(a, b) (len xs), (min a b)
Tight subtraction / division n-1, total/count n - 1, total / count
Method call with args xs.push(v) push mut xs v
Omitted call-site mut push xs v push mut xs v
Double quotes "hello" 'hello'
try/catch blocks try { ... } catch op/or args [ fallback ]

When debugging unfamiliar syntax, run veko inspect --tokens file.vk to verify [tight] vs [spaced] lexing, then validate with veko check --strict-types file.vk.