# AGENTS.md — Veko (`.vk`) Guide for LLMs & Coding Agents

This file gives AI coding agents (Claude Code, Codex, Antigravity, Cursor, GitHub Copilot, Windsurf, Zed, OpenCode) an accurate, zero-hallucination mental model for writing, type-checking, and testing idiomatic **Veko 1.0 (`.vk`)** programs.

> **Golden Rule for Agents:** Never guess stdlib or package function signatures from other languages. Run `veko doc <module>` (offline, instant) to read exact exported signatures, and always run `veko check --strict-types` and `veko test` before finishing an edit.

---

## 1. Mental Model: How Veko Syntax & Memory Work

Veko is a **prefix-word, homoiconic, whitespace-sensitive language with infix math** and **Predictable Memory, Zero Pauses, Zero Lifetimes** powered by **One Reference Only (ORO)**:

1. **No outer call parentheses or commas:** Words have fixed arity and read left-to-right like a CLI command:
   - Right: `os/write-file out_path payload`
   - Wrong: `os/write-file(out_path, payload)`
2. **Parentheses `(...)` are ONLY for grouping nested calls or math:**
   - Right: `while i < (len items) [ ... ]`, `bytes/with-cap ((len hdr) + body_len)`
   - Wrong: `len(items)` — **never** put `(` immediately after a function name!
3. **Whitespace is load-bearing (`[tight]` vs `[spaced]`):**
   - **Subtraction & division require spaces:** `n - 1` subtracts `1`; `n-1` is a single kebab-case identifier. `a / b` divides; `str/join` is a module path; `/or` is a refinement.
   - **Dots & indexing must be tight (no leading space):** `user.name`, `raw.trim.upper`, `buf[0..n]`.
   - **Enum symbols require a leading space or opener:** `mode = .tls`, `return .ok` (`x.tls` is field/UFCS access).
   - **Negative literals require a leading space before `-`:** `add x -1` passes `-1`; `x - 1` subtracts `1`.
4. **Delimiters & strings:**
   - `[ ... ]` = code blocks, parameter lists, data arrays/blocks, and slice ranges (`xs[0..n]`).
   - `{ ... }` = structs (`struct { ... }`, `Config { ... }`) and maps (`{ key = val }`).
   - `'...'` = UTF-8 string literals (`'hello\n'`). `` `hello {name}` `` = interpolated string template. `//` = line comment.
5. **One Reference Only (ORO) & Zero `nil`:**
   - Values have one owner (`a = b` moves ownership; modifying a shared slice/map triggers deterministic Copy-on-Write).
   - **In-place mutation requires `mut` at BOTH the binding/parameter AND the call site:** `mut xs = []; push mut xs 42`.
   - **Veko has NO `nil` or `null` keyword:** unit actions return `.ok`; wire/JSON `null` decodes to `.null`; missing keys or I/O failures return an `err` value handled inline with `/or [ fallback ]`.

---

## 2. Canonical `.vk` Construct Cheatsheet

### Bindings, `mut`, Functions, Refinements & Interfaces
```rebol
timeout = 5s
mut count = 0
count = count + 1

// Dynamic fn, typed fn, [T] generic fn, and /refinement optional parameters
add-one = fn [n] [ n + 1 ]
id-val  = fn [T] [x T] T [ x ]
dial    = fn [host str /port p i64 = 443] str [ `https://{host}:{p}` ]

pub encode-header = fn [name str, value str] bytes [
	bytes/from-str `{name}: {value}\r\n`
]

// In-place mutation requires `mut` at BOTH declaration AND call site
append-nl = fn [mut buf bytes] [
	_ = bytes/push mut buf 10
]
append-nl mut packet
append-nl mut conn.tx_buf

// Structural interface
pub Sink = interface { name str, emit fn[str -> str] }
```

### `struct`, `.enum`, Maps & `/or` Error Recovery
```rebol
pub Upstream = struct {
	host str,
	port i64 = 443,
	api_key secret str = ''
}

primary = Upstream { host = 'api.example.com' }
staging = primary \ struct/with { port = 8443 }
mut cur = staging
put mut cur .port 9443

// Missing map keys and fallible operations return `err` — recover inline with `/or`
host = map/get/or cfg 'host' [ '127.0.0.1' ]
port = str/to-i64/or raw_port [ 443 ]
raw  = os/read-file/or 'config.json' [e -> return (err `config missing: {mold e}`)]
```

### Pipes `\`, Control Flow, Higher-Order Closures & `defer`
```rebol
// Pipe `\` feeds the left result as argument 1 of the next word
active_urls = raw_json
	\ json/decode
	\ filter fn [u] [u.active]
	\ map fn [u] [u.url.trim]

if (len active_urls) == 0 [ return (err 'no active endpoints') ]

mut i = 0
while i < (len active_urls) [
	match mode [
		.tls   [ println active_urls[i] ]
		.plain [ println 'skipped' ]
	]
	i = i + 1
]

// Unknown-arity closure parameters/fields call with `(f arg1 ...)` or 0-arg `call f`
apply-twice = fn [f x] [ (f (f x)) ]

// LIFO cleanup on normal return OR `/or` early unwind
with-temp = fn [path str] [
	defer [ _ = os/rm/or path [ .ok ] ]
	os/read-file path
]
```

### Shared-Nothing Concurrency (`spawn`, `chan/*`) & `.secret` Hygiene
```rebol
// Isolated workers: never capture outer `mut` bindings or `.secret` values across `spawn`
ch = chan/new 8
t = spawn [
	_ = chan/send ch 'worker-ready'
	42
]
msg = chan/recv/timeout/or ch 2s [ 'timed-out' ]
ans = task/await t

// `secret` values auto-redact to `<secret>` on print/log/debug and cannot cross net/fs/json
api_tok = os/getenv/secret/or 'API_TOKEN' [ bytes/with-secret 0 ]
```

### Workspace Manifest (`veko.vk`) & Modules
```rebol
// veko.vk at project root:
{
	name = 'my-service'
	version = '0.1.0'
	root = 'src'
	entry = 'src/main.vk'
	strict-types = true
	allow-caps = [.fs .clocks .env .net]
}

// Logical module imports inside src/*.vk (never use ./ or .vk extensions):
use [web, html, sq = db/sqlite, router = http_router]
```

---

## 3. Common Mistakes from Python / TypeScript / Go / Rust

| Habit from Other Languages | Wrong in Veko | Idiomatic Veko |
| :--- | :--- | :--- |
| Call parentheses & commas | `len(xs)`, `str/join(xs, ',')` | `(len xs)`, `str/join xs ','` |
| Unspaced `-` or `/` math | `n-1`, `total/count` | `n - 1`, `total / count` |
| Double-quoted string literals | `"hello"` | `'hello'` or `` `hello {name}` `` |
| `nil` / `null` / `None` / `undefined` | `if x == nil` | `.ok` (unit), `.null` (JSON null), `map/get/or m k [ default ]` |
| Missing `mut` at call site | `push items x` | `mut items = []; push mut items x` |
| Multi-arg `.method(a, b)` calls | `items.push(x)`, `s.split(',')` | `push mut items x`, `str/split s ','` |
| `try / catch` exceptions | `try { ... } catch (e)` | `op/or arg [e -> fallback]` |
| Space before `.field` or `[idx]` | `user .name`, `xs [0]` | `user.name`, `xs[0]` |
| `PascalCase` variable before `{ ... }` | `Users = ...; insert db Users { ... }` | `users_tbl = ...; insert db users_tbl { ... }` (`PascalCase { ... }` parses as a struct literal!) |
| Tab/indentation formatting drift | 2-space mixed indentation | Run `veko fmt -w src/ tests/` |
| Guessing stdlib function names | Inventing `http/get` | Run `veko doc net/client` or `veko doc web` |

---

## 4. Agent CLI Verification & Introspection Loop

Always use the `veko` CLI directly to inspect signatures, tokens, types, capabilities, and tests:

```sh
# 1. Look up exact function signatures & examples in any built-in stdlib module (offline, instant)
veko doc web
veko doc db/sqlite
veko doc db/orm
veko doc net/client

# 2. Search, inspect, and add signed packages from https://veko-lang.org/pkg
veko pkg search rag
veko pkg info payments_ledger
veko pkg add http_router@1.2.0

# 3. Diagnose [tight] vs [spaced] tokens or AST grouping when fixing syntax errors
veko inspect --tokens src/main.vk
veko inspect --ast src/main.vk

# 4. Sync minimal capability allowlists in veko.vk from actual `use [...]` imports
veko init --sync

# 5. Static type-check, disjoint `mut` borrow check, `.secret` firewall, and capability check
veko check --strict-types

# 6. Format canonically, run unit tests + doctests, and build/execute
veko fmt -w src/ tests/
veko test
veko run
veko doctor
veko compile --native -o dist/app                 # Cross-compile: --target=win-x64|win-arm64|linux-x64|linux-arm64|macos-arm64
```

---

## 5. Built-In Stdlib (95 Modules) & Official `.vkp` Packages (30 Libraries)

### Key Embedded Standard Library Modules (`use [...]` — Zero Downloads Needed)
- **Strings, Bytes, Math & Time:** `strings`, `bytes`, `math`, `decimal`, `bigint`, `bits`, `rand`, `datetime`, `regex`, `diff`, `semver`
- **Files, Streams, CLI & Formats:** `fs`, `path`, `io`, `cli`, `slog`, `template`, `html`, `codec/csv`, `codec/toml`, `codec/cbor`, `codec/msgpack`, `codec/base64`, `codec/hex`, `archive/tar`, `archive/zip`, `compress/deflate`, `compress/zstd`
- **Networking, TLS 1.3, HTTP/1.1–HTTP/3 & Web:** `io/reactor`, `io/net`, `net`, `net/ip`, `net/dns`, `net/tls13`, `net/http`, `net/http2`, `net/http3`, `net/quic`, `net/websocket`, `net/client`, `web`
- **Databases, Caching & Durable Actors:** `db/sqlite` (100% pure-Veko Zero-FFI SQLite 3), `db/orm`, `db/pool`, `db/postgres`, `db/redis`, `kv`, `actor/durable`
- **Crypto, Post-Quantum & Auth:** `crypto/sha256`, `crypto/sha3`, `crypto/blake`, `crypto/aes`, `crypto/chacha20`, `crypto/x25519`, `crypto/p256`, `crypto/rsa`, `crypto/x509`, `crypto/mlkem`, `crypto/mldsa`, `auth/jwt`, `auth/totp`, `auth/oauth2`
- **Testing, Benchmarks, UI & FFI:** `testing`, `testing/fuzz`, `bench`, `metrics`, `trace`, `ui`, `ui/canvas`, `ui/widgets`, `tui`, `ffi`

### Official Signed `.vkp` Packages (`veko pkg add <name>@1.0.0` — `http_router@1.2.0`)
- **Tier 1 (Backend):** `cloud_s3` (S3/R2 SigV4), `data_formats` (YAML/XML/RSS/Atom), `openapi` (Schema + OpenAPI 3.1), `smtp_mail` (MIME/DKIM/SMTP), `webauthn` (Passkeys + RBAC/ABAC)
- **Tier 2 (Distributed):** `grpc_proto` (Protobuf v3 + gRPC), `cluster_raft` (Raft + SWIM gossip), `mq_streams` (NATS + Kafka), `db_drivers` (MySQL + ClickHouse), `resilience` (LRU/GCRA/Breaker/Singleflight)
- **Tier 3 (AI & Data):** `ai_mcp` (MCP Server/Client), `ai_llm` (Gemini/Anthropic/OpenAI/Ollama), `vec_rag` (HNSW + BM25 Hybrid RAG), `dataframe_parquet` (Columnar DataFrames + Arrow IPC)
- **Tier 4 (SaaS & Enterprise):** `payments_ledger` (Money + Double-Entry Ledger + Stripe), `graphql` (Schema + Dataloader + GraphiQL), `browser_cdp` (Chrome DevTools E2E), `ldap_saml` (SAML 2.0 + OIDC JWKS + SCIM 2.0)
- **Tier 5 (Cloud-Native & Security):** `oci_k8s` (Daemonless OCI + Kubernetes), `noise_tunnel` (Noise_IKpsk2 + SOCKS5), `iac_fleet` (Homoiconic IaC DAG), `wasm_plugin_sdk` (Multi-Tenant Wasm 3.0 Plugins)
- **Tier 6 (Realtime, IoT & Web):** `crdt_sync` (HLC/LWW/ORSet/RGA CRDTs), `iot_mqtt` (MQTT 5.0 + Modbus + mDNS), `web_live` (Server-Driven Live Views + HTMX), `jobs_cron` (Cron + SQLite Queue), `doc_media` (GFM Markdown + PDF + Image + SSH), `http_router` (`@1.2.0`), `veko_ui_kit`, `sqlite_orm_ext`
