# rfsh `lua` Applet API Reference (for AI Agents / Script Generation)

> Applicable environment: Windows x64 / Lua **5.5.0** / the `rfsh` embedded interpreter (both debug and release builds live-tested). Document date: 2026-11-13.
> This document describes the **host-injected APIs** and the **pure-Lua module package embedded in the runtime**; it does not repeat the Lua standard library manual.
> Notation: values after `->` are return values; entries marked **(live-tested)** were confirmed by running `rfsh lua`.
> **Safe to publish**: contains no repository root paths, user directories, build artifact paths, internal source directory hierarchies, or real host information. All example paths are placeholders; see §8.6 for the redaction conventions.
> **The embedded zip package (§2.5) is the only source of pure-Lua modules at runtime**; the `.lua` copies in the repo are development references only and may differ from the runtime version.
> **See §8 for how to generate/update this document** (AI agents should read that section first on the next update).

---

## 0. Hard Constraints for AI Agents (Read This First)

1. **The entry point is `rfsh lua`, not the system `lua`**: `rfsh lua -e 'code'`, `rfsh lua script.lua a b`.
2. **`-e` must be a single line**: a **real newline** in a command-line argument is split by the shell layer into multiple commands and reports `unfinished string`; even a `\n` escape inside a Lua string may be turned back into a real newline by the command-line layer (live test: `conf.read_str("[s]\nk=1\n")` reports `unfinished string near '"[s]'`). Put multi-line logic in a script file; when a newline character is needed inside `-e`, build it with `string.char(10)`. **(live-tested)**
3. **Use forward slashes `/` in paths** (`some/dir/file.txt`); the in-project `LUA_PATH` uses the `/?.lua` template; do not build paths with `\`.
4. **Strings are byte strings**: `os.run` / `sh.run` / `str.base64_decode` / `str.hex_decode` / `str.compress` and others all return via `lua_pushlstring` and **may contain NUL**; do not treat them as C strings, and do not `print` binary results.
5. **Error conventions are not uniform** (see §4): most functions return `nil, errmsg`, a few return **0 values**, and `speed.*` return values are unreliable. When generating code use `local a,b = ...; if not a then ... end`, and add `select('#', ...)` or `pcall` for functions that may return nothing.
6. **§2.5 is authoritative for pure-Lua modules**: the embedded package has **75 modules**, of which **61 are usable and 14 are not** (live-tested). Do not assume a module exists or is callable based on the official Penlight / LuaSocket manuals — this build is **Lua 5.5**, and a number of older libraries fail to load because `for` loop variables became const.
7. **See §2.3 for C modules**: `require('lfs')` / `require('cjson')` / `require('vfs')` are confirmed usable; `luv` / `luaio` load conditionally on specific Windows versions only. `ffi` / `nanomsg` / `lsqlite3` / `worker*` are commented out in this build — do not use them.
8. **Dangerous functions require explicit authorization**: `os.shutdown`, `os.kill`, `os.killall_regex`, `os.painc` (deliberate crash), `os.spawn` (background process). AI agents must not generate these calls unless the user explicitly asks.
9. **The `log` global table is `nil`** (live-tested). For logging use global functions such as `log_info(...)`, or `mlog.*`; never write `log.info(...)`.
10. **The `json` module must be called with a colon**: `local j = require('json'); j:encode(t)`; writing `j.encode(t)` reports `must be called in method format`. **(live-tested)**

---

## 1. Entry Points and Execution

### 1.1 Shell Entry Point (Primary Usage)

`rfunc_def(lua)` → `lua_main(argc, argv)`, i.e. the embedded standalone Lua 5.5 interpreter (compiled with `LUA_MAIN_SH`).

```sh
rfsh lua -e 'print(str.md5("abc"))'
rfsh lua -l cjson -e 'print(cjson.encode({a=1}))'
rfsh lua job.lua arg1 arg2
rfsh lua -i                    # interactive REPL
rfsh lua -v                    # version (live-tested: Lua 5.5.0 ... ran_vfile)
rfsh lua -E ...                # ignore LUA_INIT / environment variables
```

Standard options `-e / -l / -i / -v / -E / -W / --` are handled by `collectargs()`; `LUA_INIT` / `LUA_INIT_5_5` are executed when `-E` is not specified.

**The `arg` table (live-tested with `rfsh lua job.lua A B`)**:

| Key | Value |
|---|---|
| `arg[-1]` | `"lua"` (the applet name, **not** the exe path) |
| `arg[0]` | Script path (passed through unchanged) |
| `arg[1]`, `arg[2]` ... | Script arguments `A`, `B` |

In `-e` mode, `arg[0]="lua"` and `arg[1]="-e"` (live-tested). When generating scripts, **do not rely on `arg[-1]` to obtain the program path** — use `os.get_exe_path()`.

### 1.2 Embedded / qscript Entry Points (a Separate Set, Same Functionality)

- `luabox_dofile(file)` / `luabox_dofile2(file, ...args)` / `luabox_dobuf(name, buf, len)` / `luabox_dobuf2(...)`: internally `luaL_newstate()` → `luabox_openlibs()` → execute → close.
- `lua_script_drv_get()`: the qscript driver; `init` creates the state, and `run` injects `param_var` / `dyn_var` as globals before `lua_pcall`.
- The `arg` set by these two paths **differs** from §1.1: `arg[-1]` = exe path, `arg[0]` = script name, `arg[1..]` = the varargs of `dofile2`.
- The qscript driver's `run()` applies `atol(lua_tostring(L,-1))` to the return value, so **the script must return a number or a numeric string**, otherwise it panics. The standard `rfsh lua` entry point ignores the script's return value.

### 1.3 Initialization Chain (How the Embedded Package Gets Into Memory)

```
lua_main → luabox_init()      # set up the rfile vfs driver, mount the embedded zip, write LUA_PATH/LUA_EXE
         → luaL_newstate()
         → pmain → luabox_openlibs(L)  # §2: standard libs + C modules + 6 namespaces + 5 automatic requires
         → createargtable / runargs / handle_script
         → luabox_exit() → pl_exit()
```

**How the embedded package is loaded (this determines the require names in §2.5)**:

1. At build time the `utils.bin2c` rule turns the resource file `zlua.zip` into a C byte array compiled directly into the interpreter binary; **the runtime never reads `.lua` sources from disk**.
2. `luabox_init()` wraps the array address as a memory URL (`url_build_memory_addr_url`) and mounts it via the physfs driver as VFS root `0:/`; an optional second app package is mounted as `1:/`.
3. `LUA_PATH` is assembled by `add_env()` root by root as `<root>/?.lua;<root>/?/init.lua`. Roots = the VFS mount point plus a fixed subdirectory list: `""` (package root), `base`, `socket`, `cURL`, `luacov`, `lunitx`, `cliargs`, `copas`, `webdav`, `xavante`; a trailing `;;` appends Lua's default path.
4. Because the `<package root>/?.lua` wildcard exists, **any subdirectory can be required**: `pl.path` → `pl/path.lua`, `luv.utils` → `luv/utils.lua`; and since `base/?.lua` is a root, `base/log.lua` can be loaded directly with `require('log')`.
5. **`0:/` is a read-only in-memory VFS**: do not try to write files into the package; script files are still read from the host filesystem.

---

## 2. Runtime Environment (`luabox_openlibs`)

### 2.1 Injected Global Constants (read-only semantics; all strings except `_PID`, which is an integer)

| Variable | Meaning | Example (live-tested) |
|---|---|---|
| `_CPU` | CPU description string | — |
| `_MAC` | First MAC, `%012llx` | — |
| `_IP` | First IP | — |
| `_HOST` | Platform string | `"windows"` |
| `_OSINFO` | System information string | — |
| `_OSVER` | System version string | — |
| `_OSARCH` | System architecture string | — |
| `_ARCH` | Build architecture name | `"x64"` |
| `_EDIR` | Directory containing the exe | — |
| `_VER` | Product version string | `<version string>` |
| `_PID` | Process ID (integer) | — |

### 2.2 Standard Library

`luaL_openlibs(L)`: base / package / coroutine / debug / io / math / os / string / table / utf8. Note that **the `os` table is merged over by the extension functions in §3.1** (`luabox_register` fetches the existing table and then calls `luaL_setfuncs`); the original `os.execute/os.time/...` remain.

### 2.3 C Modules Preloaded and Registered as Globals (`luaL_requiref(..., 1)`)

| Module | Notes | Module | Notes |
|---|---|---|---|
| `struct` | struct packing | `buffer` | binary buffer |
| `lfs` | LuaFileSystem (live-tested, usable) | `vfs` | in-project vfs (live-tested, usable) |
| `cjson` / `cjson.safe` | JSON (live-tested, usable) | `lsqlcipher` | SQLCipher SQLite |
| `socket.core` / `mime.core` | LuaSocket | `luv` | libuv (loaded conditionally on specific Windows versions only) |
| `mbedtls` | MD/SSL/base64 | `lcurl` / `lcurl.safe` | libcurl |
| `system.core` / `term.core` | Windows only | `lpeg` / `lxp` | Windows only |
| `luachild` / `luaio` | Windows only (luaio also on specific versions only) | | |

Commented out, **unavailable**: `ffi`, `nanomsg`, `lsqlite3`, `worker`, `worker_uv`.

### 2.4 Five Modules Loaded Automatically at Startup and the Globals They Inject

At the end of `luabox_openlibs()` it runs `require('log') / ('alias') / ('base') / ('string_ex') / ('io_ex')`. **The following is based on the runtime embedded-zip versions** (the same-named source copies in the repo differ from them; do not infer behavior from those sources).

| Module (require name) | Returns | Globals injected | Notes |
|---|---|---|---|
| `log` | table | `log_trace`, `log_debug`, `log_info`, `log_warn`, `log_error`, `log_fatal`, `log_hexdump`, `log_objdump`, `log_set_level`, `log_init_conf` | All are functions (live-tested). They accept `(fmt, ...)`, apply `string.format` internally, and call `mlog.trace`. Log lines carry the `__lua__():` call site (live-tested) |
| `alias` | `true` | `base64 = { encode = str.base64_encode, decode = str.base64_decode }`, `_SEP` | `base64` is a table (live-tested); the `alias` global itself is nil (live-tested) |
| `base` | `true` | `lua_get_script_dir(level)`, `lua_add_script_dir_to_path(level, sub_dir)` | Adds the script directory to `package.path` |
| `string_ex` | `true` | `string:contains/startswith/endswith/replace/insert`, `string.gfind = string.gmatch` | Extends the standard `string` metatable (live-tested: `string.contains` is a function) |
| `io_ex` | `true` | `io_read_all`, `cat`, `io_write_all`, `put`, `io_write_str_all`, `put_text`, `io_popen_read_all_trim`, `cmd_output` | `cat` / `cmd_output` are functions (live-tested) |

> **Why the `log` global table is nil**: the zip version declares `local log = {...}` and ends with `log_trace = log.trace; ...; return log`. The module uses a **local**, and the startup code discards the value returned by `require`, so `_G.log` is never assigned; only the 10 `log_*` global functions are exported. The repo copy that relies on a global `log` table **is not the version in effect at runtime**.
>
> Chunks with no `return` statement (`alias` / `base` / `string_ex` / `io_ex`) leave `package.loaded` set to `true` after `require`, so they return **boolean true**; **do not treat the return value as a module table**.

### 2.5 Embedded Pure-Lua Module Package (Complete List, 75 Modules)

The resource package is `zlua.zip`, mounted at in-memory VFS `0:/` via the mechanism in §1.3. **Require-name mapping rules**:

| Package entry | Require name | Example |
|---|---|---|
| `base/xxx.lua` | `xxx` (no prefix) | `base/log.lua` → `require('log')` |
| `pl/xxx.lua` | `pl.xxx` | `pl/path.lua` → `require('pl.path')` |
| `pl/init.lua` | `pl` | `require('pl')` |
| `socket/xxx.lua` | `socket.xxx` | `socket/url.lua` → `require('socket.url')` |
| `luv/xxx.lua` | `luv.xxx` | `luv/utils.lua` → `require('luv.utils')` |

Package names are case-sensitive (`pl.Date`, `pl.List`, `pl.Map`, `pl.MultiMap`, `pl.OrderedMap`, `pl.Set`, `tableUtils`). The "returns" column comes from **live-run iteration** over `pairs(require(...))`; an empty `pairs` does not mean there is no API — see §2.6.

### A. `base/` — Top-Level Requires (No Prefix) (24 modules, 24 usable)

| require | Returns | Purpose | Status |
|---|---|---|---|
| `alias` | boolean | Global aliases: the `base64` table and `_SEP` (path separator) | Available |
| `ansicolors` | table | Terminal ANSI color string constants | Available |
| `argparse` | table | Command-line argument parser (factory via metatable `__call`; exports only `version`) | Available |
| `base` | boolean | Helper that adds the script directory to `package.path` | Available |
| `binaryheap` | table | Binary heap: minHeap/maxHeap/minUnique/maxUnique | Available |
| `bitop` | table | Pure-Lua bitwise operations, including bit32/bit compatibility layers | Available |
| `coxpcall` | table | Coroutine-safe pcall / xpcall | Available |
| `debugger` | table | Interactive debugger (**prints two version lines when loaded**) | Available (side effects, see §2.6) |
| `dumbParser` | table | Lua source parsing / AST rewriting / minification | Available |
| `inspect` | table | Pretty-print table structures (`inspect(x, opts)`) | Available |
| `io_ex` | boolean | Global helpers for file and command I/O (`cat`/`put`/`cmd_output`) | Available |
| `json` | table | JSON encoding/decoding (`json.encode/decode`, exported via metatable, `pairs` is empty) | Available |
| `log` | table | Logging wrapper; exports 10 `log_*` global functions | Available |
| `luaunit` | table | Unit test framework (LuaUnit) | Available |
| `mediator` | table | Publish/subscribe event bus | Available |
| `mobdebug` | table | Remote debugger client | Available |
| `msgpack` | table | MessagePack encoding/decoding | Available |
| `profiler` | table | Performance sampling / call statistics | Available |
| `re` | table | Regex library (Roberto's re, depends on lpeg) | Available |
| `string_ex` | boolean | Extends standard `string`: contains/startswith/endswith/replace/insert | Available |
| `tableUtils` | table | Table utilities | Available |
| `timer` | table | Timers (clock function is replaceable) | Available |
| `timerwheel` | table | Timing-wheel timers | Available |
| `url` | table | URL parsing and construction (net/url) | Available |

### B. `pl/` — Penlight (39 modules, 26 usable)

| require | Returns | Purpose | Status |
|---|---|---|---|
| `pl` | boolean | Injects Penlight submodules into `_G` on demand (**rewrites the `_G` metatable**) | Available (side effects, see §2.6) |
| `pl.Date` | table | Dates and formatting | Available |
| `pl.List` | — | Python-style List | **Unavailable**: Lua 5.5 const conflict |
| `pl.Map` | — | Map class | **Unavailable**: Lua 5.5 const conflict |
| `pl.MultiMap` | — | Multi-value Map | **Unavailable**: Lua 5.5 const conflict |
| `pl.OrderedMap` | — | Insertion-ordered Map | **Unavailable**: Lua 5.5 const conflict |
| `pl.Set` | — | Set | **Unavailable**: Lua 5.5 const conflict |
| `pl.app` | — | Application support: command-line flag parsing | **Unavailable**: Lua 5.5 const conflict |
| `pl.array2d` | — | 2D array operations | **Unavailable**: Lua 5.5 const conflict |
| `pl.class` | table | Class and inheritance framework | Available |
| `pl.compat` | table | Lua 5.1/5.2/5.3 compatibility layer | Available |
| `pl.comprehension` | table | List comprehensions | Available |
| `pl.config` | table | Read config files into Lua tables | Available |
| `pl.data` | table | Reading and querying tabular data | Available |
| `pl.dir` | table | Directory listing, path creation | Available |
| `pl.file` | table | File read/write, move, copy | Available |
| `pl.func` | — | Functional composition / binding / placeholder expressions | **Unavailable**: Lua 5.5 const conflict |
| `pl.import_into` | function | Penlight on-demand loader (returns a function) | Available |
| `pl.input` | table | Iterators that extract words/numbers from input sources | Available |
| `pl.lapp` | — | Command-line parsing from human-readable specs | **Unavailable**: Lua 5.5 const conflict |
| `pl.lexer` | table | Lexical scanner | Available |
| `pl.luabalanced` | table | Extracts bracket-balanced Lua snippets | Available |
| `pl.operator` | table | Turns Lua operators into functions | Available |
| `pl.path` | table | Path operations and file queries | Available |
| `pl.permute` | — | Permutation operations | **Unavailable**: Lua 5.5 const conflict |
| `pl.pretty` | table | Pretty-print tables | Available |
| `pl.seq` | — | Treat iterators as sequences | **Unavailable**: Lua 5.5 const conflict |
| `pl.sip` | table | Simple Input Patterns | Available |
| `pl.strict` | table | Undeclared-global checks (**rewrites `_G` to be strict by default**) | Available (side effects, see §2.6) |
| `pl.stringio` | table | String I/O on file-like objects | Available |
| `pl.stringx` | table | Python-style extended string library | **Partially available**: loads, but `split` etc. lazy-load `pl.tablex` and then hit a const error (see §2.6) |
| `pl.tablex` | — | Extended table operations (dependency of most Penlight modules) | **Unavailable**: Lua 5.5 const conflict |
| `pl.template` | table | Template preprocessor | Available |
| `pl.test` | — | Test utilities | **Unavailable**: Lua 5.5 const conflict |
| `pl.text` | table | Text processing utilities | Available |
| `pl.types` | table | Detailed type information | Available |
| `pl.url` | table | Python-style URL quoting | Available |
| `pl.utils` | table | General utilities (Penlight foundation) | Available |
| `pl.xml` | table | XML LOM utilities | Available |

### C. `socket/` — Pure-Lua Layer of LuaSocket (10 modules, 10 usable)

| require | Returns | Purpose | Status |
|---|---|---|---|
| `socket.ftp` | table | FTP client | Available |
| `socket.headers` | table | HTTP header field normalization | Available |
| `socket.http` | table | HTTP/1.1 client | Available |
| `socket.ltn12` | table | LTN12: filter / source / sink / pump | Available |
| `socket.mbox` | table | mbox mailbox parsing | Available |
| `socket.mime` | table | MIME encoding/decoding support | Available |
| `socket.smtp` | table | SMTP client | Available |
| `socket.socket` | table | LuaSocket high-level helpers | Available |
| `socket.tp` | table | Common SMTP/FTP subsystem | Available |
| `socket.url` | table | URI parsing, composition, relative URL resolution | Available |

### D. `luv/` (2 modules, 1 usable)

| require | Returns | Purpose | Status |
|---|---|---|---|
| `luv.tap` | — | TAP test output (depends on `lib/utils`, missing from the package) | **Unavailable**: missing dependency `lib/utils` |
| `luv.utils` | table | libuv helper functions | Available |

**Two causes of unusable modules** (live-tested; AI agents must avoid these when generating scripts):

| Cause | Affected modules | Error signature |
|---|---|---|
| **Lua 5.5 makes the loop variables of `for k,v in ...` const**; older Penlight reassigns `k` / `v` inside the loop body | 13 `pl.*` modules (see the table above) | `attempt to assign to const variable 'k'` (typical locations: `pl/tablex.lua:106`, `pl/app.lua:197`, `pl/seq.lua:129`) |
| Missing dependency inside the package | `luv.tap` | `module 'lib/utils' not found` |

`pl.tablex` is a shared dependency of most Penlight collection modules; once it breaks, `pl.List` / `pl.Map` / `pl.Set` / `pl.array2d` / `pl.func` / `pl.seq` / `pl.test` / `pl.permute` / `pl.app` / `pl.lapp` and others **all break with it**. Of the 26 loadable `pl*` modules, `pl.stringx` is "loadable but partially unusable" (see §2.6).

### 2.6 Quick Reference for Key Third-Party Modules (Live-Tested Exports / Side Effects)

All keys below were obtained from live runs of `pairs(require(name))`; only high-frequency entries are listed. Use the probe in §8.4 to re-extract the complete list.

| Module | Live-tested exports (excerpt) | Minimal working example |
|---|---|---|
| `json` | `pairs` is empty; **methods are exported via the metatable**: `encode/decode/encode_pretty` | `local j=require('json'); print(j:encode({a=1}))` **(live-tested; the colon is mandatory)** |
| `inspect` | `inspect`, `KEY`, `METATABLE`, `Options` | `print(require('inspect')({1,2,x=3}))` → `{ 1, 2,   x = 3 }` **(live-tested)** |
| `msgpack` | `encode/decode/encode_one/decode_one` | `local m=require('msgpack'); print(m.decode(m.encode({1,2}))[2])` → `2` **(live-tested)** |
| `bitop` | `band/bor/bxor/bnot/lshift/rshift/tobit/tohex/...` plus `bit`/`bit32` subtables | `require('bitop').band(3,1)` → `1.0` (float) **(live-tested)** |
| `url` (net/url) | `parse/build/parseQuery/buildQuery/resolve/normalize/...` | `require('url').parse('http://example.com/y')` |
| `socket.url` | `parse/build/parse_path/build_path/escape/unescape/absolute` | `require('socket.url').parse('http://example.com/y').path` → `/y` **(live-tested)** |
| `tableUtils` | `t2s/s2t/copyTable/mergeArrays/diffTable/patch/inArray` | `require('tableUtils').t2s({a=1})` → `{["a"]=1,}` **(live-tested)** |
| `binaryheap` | `minHeap/maxHeap/minUnique/maxUnique/binaryHeap` | See the comments inside the package for constructor usage; `pairs` alone is not enough to infer the calling convention |
| `timer` | `timeout/async/sleep/update/remove` | — |
| `timerwheel` | `new` | — |
| `re` | `compile/match/find/gsub/updatelocale` (depends on lpeg) | — |
| `mediator` | `Channel`, `Subscriber` (both functions) **(live-tested)** | — |
| `argparse` | Exports only `version`; factory via metatable `__call` | `local p = require('argparse')("name","desc")` |
| `pl.path` | `abspath/basename/dirname/join/split/...` | `require('pl.path').basename('a/b/c.txt')` → `c.txt` **(live-tested)** |
| `pl.dir` | `getfiles/getdirectories/getallfiles/walk/dirtree/makepath/...` | — |
| `pl.file` | `read/write/copy/move/delete/access_time/...` | — |
| `pl.pretty` | `write/dump/read/load/debug/number` | — |
| `pl.utils` | `split/escape/execute/bind1/bind2/choose/...` | — |
| `pl.class` | `properties` plus a metatable constructor | — |
| `socket.http` | `request/open/genericform`, `TIMEOUT`, `USERAGENT` | — |
| `luv.utils` | `dump/prettyPrint/color/colorize/uvVersionGEQ`, `stdout` | — |

**Modules with side effects (AI agents should use with care)**:

| Module | Side effect |
|---|---|
| `pl` (`pl/init.lua`) | `require('pl.import_into')(_G)` **rewrites the `_G` metatable**; afterwards, accessing an undefined global lazily loads a Penlight submodule on demand, which can mask typos |
| `pl.strict` | Makes `_G` strict by default, so reading/writing undeclared globals raises immediately; **breaks subsequent scripts** — use it alone, at the very end |
| `pl.import_into` | Returns a function that clobbers the metatable of the table passed to it when called |
| `debugger` | Prints two version lines to stdout on load (live-tested: `Not tested against Lua 5.5` / `Please send me feedback!`), polluting machine-readable output |
| `pl.stringx` | `pairs` works and the module loads, but calling `split` etc. **lazy-loads `pl.tablex`** and triggers a const error (live-tested). **Treat it as unavailable** |

> **"require succeeded" != "callable"**: this build has two traps — metatable exports (`json`, `argparse` have nearly empty `pairs`) and lazy dependencies (`pl.stringx`). When generating code, prefer the live-tested examples in the table above; for everything else, try it once with `pcall` first.

---

## 3. Namespace APIs

### 3.1 `os.*` — Process / System Extensions (22 functions)

Common arguments:

```
envs : nil | { "K=V", ... } | { K="V", ... }        -- environment passed to the child process
opts : nil | wait_ms[, flag] | {
         wait_timeout = ms,    -- default -1 = wait forever
         shell        = bool,  -- default true
         user_mode    = bool,
         flag         = n,     -- additional bitwise OR
         user         = "name" -- read only by os.spawn
       }
```

| Function | Returns | Notes |
|---|---|---|
| `os.execute2(cmd [, envs [, opts]])` | On success `true, "exit", code`; on failure `nil, errmsg` | `luaL_execresult`. Command output goes **straight to stdout** (live test: `echo hi` → `hi` / `true exit 0`). With `cmd=nil` it only probes shell availability and returns `true` |
| `os.run(cmd [, envs [, opts]])` | `exit_code, stdout, stderr` (3 values; live-tested `0,string,string`) | Captures output, binary-safe; a missing `cmd` raises `luaL_error` |
| `os.spawn(cmd [, envs [, opts]])` | `pid` or `nil, ret` | Starts in the background and returns immediately, **without waiting** (live-tested pid + `os.pid_running(pid)==1`). The caller is responsible for `wait_pid` / `kill` |
| `os.wait_pid(pid [, timeout_ms])` | `ret, exit_code\|nil` | `ret`: `0` = exited, `-2` = timed out and still running, `-1` = error; `timeout_ms` defaults to `-1` (infinite), `0` = poll |
| `os.pause()` | none | Prints a prompt and waits for any key; **blocks** |
| `os.sleep_ms(ms)` | none | Supports fractional milliseconds, e.g. `0.5` |
| `os.mclock()` | integer | Monotonic millisecond clock |
| `os.time_ms()` | integer | `tv_sec*1000 + tv_nsec/1e6` (live-tested >0) |
| `os.get_exe_path()` | string | Full path of the current exe (live-tested, non-empty) |
| `os.get_pid_path(pid)` | string \| nil | Image path of the process with that pid |
| `os.pidof(name)` | `{ pid, ... }` | Finds pids by process name |
| `os.pidof2(name)` | `{ {[1]=pid,[2]=cmdline}, ... }` | Includes the command line |
| `os.pid_running(pid)` | `1` running / `0` exited / `-1` unknown | |
| `os.kill(pid_or_array)` | none | Argument may be a single pid or an array of pids |
| `os.pidof_regex(pattern)` | `{ {[1]=pid,[2]=cmdline}, ... }` | POSIX extended regex, case-insensitive, substring match after command-line normalization |
| `os.killall_regex(pattern)` | `{ pid, ... }` | Kills matching processes and returns their pids; **never kills itself** |
| `os.shutdown(t)` | none | **Dangerous**. `-h`/`-s` = shutdown, `-p` = power off, `-r` = reboot |
| `os.get_active_ipv4()` | string | IPv4 of the active NIC, `""` on failure |
| `os.get_active_mac()` / `os.get_min_mac()` | string | 12-character lowercase hex MAC, `""` on failure |
| `os.painc()` | — | **Dangerous**: deliberately dereferences NULL to trigger a crash/panic (the spelling really is `painc`); for debugging the crash path only |
| `os.urandom(n)` | n-byte binary string | Cryptographically secure random bytes |

### 3.2 `sh.*` — Command Execution via libsh (4 functions)

| Function | Returns | Notes |
|---|---|---|
| `sh.execute(cmd)` | `true,"exit",code` / `nil,errmsg` | `libsh_system`; the command goes through the libsh applet chain |
| `sh.run(cmd)` | `ret, stdout, stderr` (3 values, live-tested) | `libsh_run`; captures output, binary-safe |
| `sh.set_pipe_run_debug(bool)` | none | Toggles debug output from `pipe_run` |
| `sh.pipe_run(cmd, input)` | `ret, stdout, stderr` (3 values) | **Creates no process**; runs an applet pipeline in-process. `cmd` is an applet command string with `\|` joining stages (e.g. `awk\|sort`), and `input` is the input text. Live test: `sh.pipe_run("cat","hello pipe\n")` → `0, "hello pipe\n", ""` |

> `sh.run` / `sh.pipe_run` map a string like `"awk|xxx|sort"` to `rfsh awk | xxx | rfsh sort`.

### 3.3 `str.*` — Strings / Digests / Encoding / Compression / Encryption (25 functions, including Windows-only `a2t`)

| Function | Returns | Notes |
|---|---|---|
| `str.sed(text, script)` | string \| nil | Runs the rfsh `sed` engine on in-memory text. **(live-tested)** `str.sed("a1\na2","1p")` returns `"a1\na1\na2"` (sed auto-prints by default, so `p` in the script duplicates the output) |
| `str.awk(text, script)` | string \| nil | Runs the rfsh `awk` engine on in-memory text |
| `str.md5(s)` | 32-character lowercase hex | Live test: `abc` → `900150983cd24fb0d6963f7d28e17f72` |
| `str.sm3(s)` | 64-character lowercase hex | SM3 (Chinese national standard) |
| `str.base64_encode(s)` / `str.base64_decode(s)` | string | Binary-safe (live test: `abc`↔`YWJj`) |
| `str.hex_encode(s)` / `str.hex_decode(s)` | string | Live test: `"AB"`→`4142`, `4142`→`AB` |
| `str.url_args_encode(s)` | string | URL argument escaping |
| `str.compress(algo, data)` | string \| `nil, errmsg` | **algo can only be** `none` / `lz4` / `z` / `lzo` / `lzma` (all five verified usable in this build); any other name returns `nil,"unsupported compression algorithm"` |
| `str.decompress(algo, data)` | string \| `nil, errmsg` | The decompression buffer is sized at **4x the compressed length**, so highly compressible data may return `nil,"decompression failed"` |
| `str.cipher_encode(ctype, key_hex, data)` | string | See the algorithm table below; **an invalid ctype returns 0 values** (not `nil,err`) |
| `str.cipher_decode(ctype, key_hex, data)` | string | Same as above |
| `str.bwith(s, prefix)` / `str.ewith(s, suffix)` | boolean | Prefix/suffix test (live-tested true) |
| `str.find(s, sub)` | boolean | Substring existence (note: differs from the return values of standard `string.find`) |
| `str.match(s, pattern)` | boolean | Regex match |
| `str.glob(s, pattern)` | boolean | Wildcard matching (live test: `a.txt` vs `*.txt` → true) |
| `str.a2t(s)` | string \| nil | **Windows only**, ANSI → UTF-8 |
| `str.remove_utf8bom(s)` | string | Strips a leading `EF BB BF` (live test → `abc`) |
| `str.delchars(s, chars)` | string | Removes a set of characters (live test: `"a-b-c","-"` → `abc`) |
| `str.trim(s)` | string | Strips leading/trailing whitespace (live-tested) |
| `str.sort(s)` | string | Sorts characters by ascending byte value (live test: `cba`→`abc`) |
| `str.conf_dec(s)` | string | Decrypts if the host has installed a config decryption callback, otherwise `""` |
| `str.csv2table(s [, key_sep [, max_item [, line_sep]]])` | `{ {col1,col2,...}, ... }` | Defaults: `key_sep="\t"`, `line_sep="\n"`, `max_item=0` (live test: `[1][2]=="b"`). When `max_item!=0`, every field is trimmed |

**`cipher_*` ctypes (all verified usable)**: `aes_256_ecb`, `aes_128_ecb`, `sm4`, `rc4`.
`key_hex` is a **hexadecimal string** (written internally into a 32B key buffer); the output is a byte string after block padding (live test: 16B input → 32B output). Names like `"aes"` / `"des"` / `"xor"` are invalid.

### 3.4 `conf.*` — INI Configuration (3 functions + 8 object methods)

| Function | Returns | Notes |
|---|---|---|
| `conf.open(path [, create])` | `cfg` userdata \| `nil, errmsg` | With `create=true` it uses create-load, otherwise a plain load. The object has a `__gc` metamethod for automatic release |
| `conf.read(path)` | table \| `nil, errmsg` | Reads the whole file into a nested table in one shot and releases the handle |
| `conf.read_str(text)` | table \| `nil, "invalid config string"` | Parses ini text (live-tested) |

`cfg` methods (**colon calls**; an empty section `""` denotes root keys):

| Method | Returns |
|---|---|
| `cfg:get(section, key)` / `cfg:get(key)` | string \| nil |
| `cfg:set(section, key, val)` / `cfg:set(key, val)` | `true` \| `nil, errmsg`; val may be string / number / boolean (booleans become `"true"`/`"false"`) |
| `cfg:remove(section [, key])` | boolean (true only if it existed and was removed; omitting/emptying key deletes the whole section) |
| `cfg:has(section [, key])` | boolean (omitting key checks the section) |
| `cfg:section(section)` | `{ key = value, ... }` (all values are strings) |
| `cfg:sections()` | `{ section, ... }` array |
| `cfg:save()` | `true` \| `nil, errmsg` |
| `cfg:close()` | none; calling any method afterwards raises `conf: object already closed` |

> **`conf.read` / `read_str` perform value type conversion** (the easiest pitfall to hit):
> `true/false/yes/no/1/0` etc. → **boolean**, pure numeric strings → **number**, strings containing commas → **array** (converted recursively), everything else → string.
> Live test: `conf.read_str("[s]\nk=1\nflag=true\nlist=1,2,3\n").s.k` is **`true` (boolean), not `1`**; `list` is an array of length 3.
> When you need raw strings, use `conf.open()` + `cfg:get()`.

### 3.5 `mlog.*` — Low-Level Logging (4 functions)

Normally wrapped by the `log` module; **AI agents should prefer the `log_*` global functions in §2.4**.

| Function | Arguments | Returns |
|---|---|---|
| `mlog.trace(level, tag, traceback_str, msg)` | level per the table below | none |
| `mlog.hexdump(level, tag, traceback_str, hex, msg)` | hex may contain NUL (length taken with `lua_rawlen`) | none |
| `mlog.init_conf(conf_str)` | logging config text | none |
| `mlog.set_level(level)` | integer level | none |

Levels: `LOG_VERB=8, LOG_DEBUG=7, LOG_INFO=6, LOG_WARN=4, LOG_ERROR=3, LOG_CRIT=2`.
`traceback_str` is normally `debug.traceback("")`; the host parses `file:line` / the function name from line 3 for the log prefix.

### 3.6 `speed.*` — Progress Statistics (3 functions)

| Function | Returns | Notes |
|---|---|---|
| `speed.open(mode, total_size)` | lightuserdata | `mode` must be `read_file_mode` / `item_inc_mode` / `watch_var_mode` / `dl_file_mode`; a bad argument returns `nil, "...(invalid mode/count)!"` |
| `speed.show(h, count)` | **Unreliable** | Side effect: prints a progress line (live test output `1.00% all=10bytes ...`) |
| `speed.close(h)` | **Unreliable** | Releases the handle |

> In the implementation, `close/show` declare `return 1` but never push a value, so what actually comes back is stale stack residue (live test: `speed.show` → `10`, `speed.close` → `"userdata: ..."`). **Ignore their return values** and use them only for their side effects.

---

## 4. Type and Error Conventions

| Case | Convention | Functions involved |
|---|---|---|
| Wrong argument type | `luaL_error` (raises a Lua error; catch with `pcall`) | The `luaL_checkstring/checkinteger` family, e.g. `os.run` without cmd, or a call after `conf:close` |
| Business failure | `nil, errmsg` (`luabox_return_error` is `pushnil + pushliteral + return 2`) | `speed.open/show/close`, `conf.open/read/set/save`, `str.compress/decompress` |
| Failure with **no return value** | Returns 0 values | Invalid algorithm name in `str.cipher_*`, allocation failure in `str.base64_*`/`hex_*`, `nil` when `str.sed/awk` returns NULL |
| Boolean query | `boolean` | `str.bwith/ewith/find/match/glob`, `conf:has/remove` |
| Command execution | Three values from `luaL_execresult`, or `ret, out, err` | `os.execute2`/`sh.execute` vs `os.run`/`sh.run`/`sh.pipe_run` |
| Binary data | `lua_pushlstring`, preserves NUL | `os.run`, `sh.run`, `sh.pipe_run`, `str.*_decode`, `str.compress` |
| Third-party module loading | `require` raises (needs `pcall`) | Lua 5.5 const conflicts and missing dependencies, see §2.5 |

**Dangerous / side-effect list (AI agents must confirm user intent before generating)**: `os.shutdown`, `os.kill`, `os.killall_regex`, `os.spawn` (leaves background processes), `os.painc` (deliberate crash), `os.pause` (blocks for a keypress), `str.cipher_*` (silently returns 0 values for invalid names), `require('pl')` / `require('pl.strict')` (rewrites `_G`).

---

## 5. Copy-Paste Templates

```lua
-- 5.1 Execute a command and capture its output (three return values, binary-safe)
local rc, out, err = sh.run("head -n 2 input.txt")
if rc ~= 0 then log_error("head failed: %s", err) end
print(out)

-- 5.2 In-process pipeline; creates no child process
local rc, out = sh.pipe_run("grep|sort", "b\na\nc\n")

-- 5.3 Run an external program with a timeout and environment variables
local ok, how, code = os.execute2("mytool --run",
    { MY_FLAG = "1", PATH = os.getenv("PATH") },
    { wait_timeout = 5000, shell = false })

-- 5.4 Background task and reaping
local pid = os.spawn("longjob.exe", nil, { shell = false })
local st, exit_code = os.wait_pid(pid, 3000)
if st == -2 then os.kill(pid) end

-- 5.5 Reading config: use open+get for raw strings, read for a structured table
local cfg, e = conf.open("app.ini")
if not cfg then error(e) end
local port = cfg:get("server", "port")
cfg:close()

local t = conf.read("app.ini")   -- note: values are converted to boolean/number/array

-- 5.6 Text processing and digests
local clean = str.remove_utf8bom(cat("input.txt"))
print(str.md5(clean), str.sm3(clean))
local packed, pe = str.compress("lz4", clean)
local back = str.decompress("lz4", packed)
print(str.glob("a.txt", "*.txt"), str.trim("  x  "))

-- 5.7 Logging and global information
log_info("host=%s arch=%s pid=%s", _HOST, _ARCH, tostring(_PID))
log_objdump(t, "config")

-- 5.8 Script arguments (rfsh lua job.lua A B)
local a, b = arg[1], arg[2]

-- 5.9 Embedded package: JSON (colon calls are mandatory) and Penlight paths
local j = require("json")
print(j:encode({ ok = true }))
local path = require("pl.path")
print(path.basename("some/dir/file.txt"))

-- 5.10 Safely load modules that may be unavailable
local ok, mod = pcall(require, "pl.tablex")
if not ok then log_warn("Penlight tablex unavailable: %s", tostring(mod)) end
```

---

## 6. Verified Pitfalls (Ordered by Likelihood of Being Hit)

1. A `-e` argument containing a real newline (or a `\n` escape turned back into a newline by the command-line layer) → split into multiple commands with `unfinished string`. Use a script file, or `string.char(10)`. **(live-tested)**
2. `arg[-1]` is `"lua"`, not the exe path; use `os.get_exe_path()` for the path. **(live-tested)**
3. `conf.read*` turns `k=1` into boolean `true`; use `conf.open()+cfg:get()` when you need a string. **(live-tested)**
4. The `log` global table is `nil`; the `log_info` and other global functions work. Reason: the zip version uses `local log` and exports only `log_*`. **(live-tested)**
5. The algorithm names for `str.compress` are `none/lz4/z/lzo/lzma`, **not** `zlib/gzip/zstd/bzip2/deflate` (all of the latter were live-tested to return `nil,"unsupported compression algorithm"`).
6. The algorithm names for `str.cipher_*` are `aes_256_ecb/aes_128_ecb/sm4/rc4`, not `aes/des/xor` (invalid names return 0 values without an error).
7. `speed.show/close` return stale stack residue; just ignore them. **(live-tested)**
8. `str.sed` inherits sed's auto-print semantics, so a `1p` script prints the first line twice. **(live-tested)**
9. `os.execute2` does not capture output and passes it straight through to the parent stdout; `sh.run` / `os.run` capture it and leave the handling to the caller. **(live-tested)**
10. `os.pause()` blocks waiting for a keypress; never put it in an unattended script.
11. The standard `rfsh lua` entry point ignores the script's return value; the qscript driver entry point requires a value that `atol` can parse.
12. `luv` / `luaio` load on Windows only when certain version conditions hold; do not depend on them unconditionally.
13. **Lua 5.5 `for` loop variables are const** → 13 Penlight modules fail `require` with `attempt to assign to const variable`. **Do not generate** code involving `pl.List` / `pl.Map` / `pl.Set` / `pl.tablex` / `pl.seq` / `pl.array2d` / `pl.func` / `pl.test` / `pl.permute` / `pl.app` / `pl.lapp` / `pl.OrderedMap` / `pl.MultiMap`. **(live-tested)**
14. `require('pl')` / `require('pl.strict')` / `require('pl.import_into')` **rewrite the `_G` metatable**, masking typos or making later global assignments fail; do not use them in unattended scripts. **(live-tested)**
15. `require('debugger')` prints two version lines to stdout, polluting machine-readable output. **(live-tested)**
16. `luv.tap` depends on `lib/utils`, which does not exist in the package, so it fails to load. **(live-tested)**
17. `json` requires `j:encode(t)` / `j:decode(s)`; dot calls report `must be called in method format`. **(live-tested)**
18. `json` / `argparse` etc. **export via a metatable**, so `pairs()` does not show their main functions; `pl.stringx` is the opposite — `pairs` works and the module loads, but `split` lazy-loads `pl.tablex` and hits a const error. **"require succeeded" does not mean "callable"**. **(live-tested)**
19. **The runtime only knows the embedded zip package**: the `.lua` source copies in the repo may differ from it (the `log` module is one example); do not infer runtime behavior from the sources. **(live-tested)**
20. Modules without a `return` statement — `alias` / `base` / `string_ex` / `io_ex` / `pl` etc. — return **boolean true** from `require`, not a module table. **(live-tested)**

---

## 7. Implementation Location Hints (Search by Symbol, No Paths)

> This section provides **search anchors only**, for locating implementations when regenerating the document; it records no directory hierarchies. See §8.1.

| What to find | Search these symbols / filenames |
|---|---|
| `lua` command registration | `rfunc_def(lua)`, `func_info_def` |
| CLI options, the `arg` table, the embedded package byte array | `lua_main`, `pmain`, `g_lua_zlib` |
| Library initialization, embedded package mount, `LUA_PATH`, registration of the 6 namespaces | `luabox_init`, `luabox_mount_zip_vfs`, `add_env`, `luabox_openlibs`, `luabox_register` |
| Embedded entry points | `luabox_dofile`, `luabox_dobuf`, `lua_script_drv_get` |
| Error conventions | `luabox_return_error` |
| The six function tables | `g_osex_functions`, `g_sh_functions`, `g_string_functions`, `g_conf_functions`, `g_log_functions`, `g_speed_functions` |
| Compression / encryption algorithm names | `pack_t.name`, the encryption type enum |
| Embedded pure-Lua module package | Filename `zlua.zip` (build rule `utils.bin2c`) |

---

## 8. How to Generate / Update This Document (for AI Agents)

> Goal: after the next host API or embedded package upgrade, be able to **regenerate this MD completely** instead of patching it from human memory. Every step uses **filename / symbol searches only** and depends on no absolute paths.

### 8.1 Authoritative Data Sources (by Priority)

| # | Data | How to locate | What it provides |
|---|---|---|---|
| 1 | **Embedded pure-Lua module package** `zlua.zip` | Glob the filename in the repo (the `utils.bin2c` build rule references it) | The complete module list for §2.5, require-name mapping, module purposes |
| 2 | Registration source `lua_libs.c` | Glob the filename / Grep `luabox_openlibs` | §1.3, §§2.1–2.4, §7, the C module list, the 5 automatic requires |
| 3 | The six `luaL_Reg` function tables | Grep the six symbols such as `g_osex_functions` | The complete function names for §§3.1–3.6 |
| 4 | Individual function implementations (find files by symbol) | Grep the function name | Argument counts, return values, error conventions, algorithm names |
| 5 | Interpreter entry `lua.c` / embedded entry `luabox.c` | Glob filenames | CLI and `arg` table semantics for §1.1 / §1.2 |
| 6 | **Live-run results** | `rfsh lua` (see §8.4) | All **(live-tested)** marks and usable/unusable statuses |

**Priority rule, absolute**: **live runs > embedded zip contents > registration source > `.lua` source copies in the repo**. The same-named `.lua` copies in item 4 may differ from the zip and are reference material only (see pitfall #19).

### 8.2 Extracting the Host APIs

1. Grep the six `luaL_Reg` table names and take the `{ "name", func }` entries from each array → the complete function set and counts for §3.
2. For each `func`, read its implementation and record: `luaL_check*` arguments, `lua_push*` return values, uses of `luabox_return_error` / `luaL_error`, and the numeric `return` value.
3. Pay special attention to cases with **fewer returned values than declared** (`speed.show/close`), cases that **return 0 values** (invalid name in `str.cipher_*`), and the binary-safe semantics of `lua_pushlstring`.
4. Do not guess algorithm names: compression names come from `pack_t.name`, encryption names from the encryption type enum — run one verification for each.

### 8.3 Extracting the Embedded Package Module List

Read it into memory with Python at the repo root (**do not extract it to disk**):

```python
import zipfile, json
z = zipfile.ZipFile("<repo>/zlua.zip")   # relative path obtained by Glob
names = []
for n in z.namelist():
    if not n.endswith(".lua"):
        continue
    if n.startswith("base/"):
        names.append(n[5:-4])                    # base/log.lua -> log
    elif n == "pl/init.lua":
        names.append("pl")                       # pl/init.lua  -> pl
    elif n.startswith(("pl/", "socket/", "luv/")):
        p = n.split("/", 1)
        names.append(p[0] + "." + p[1][:-4])     # pl/path.lua  -> pl.path
    else:
        names.append(n[:-4])
json.dump(names, open("module_names.json", "w"))
```

Take the first meaningful sentence of each module's header comment as its purpose description (filtering out license / `@module` / separator lines), then polish it into a single English line.

### 8.4 Live-Run Verification Template (Mandatory; the Status Column Must Not Be Guessed)

**Probe A: can it be required + return type + exported keys** (write it to a `.lua` file, do not use `-e`):

```lua
-- probe.lua : rfsh lua probe.lua <require-name>
local name = arg[1]
local ok, m = pcall(require, name)
if not ok then
    print("ERR\t" .. name .. "\t" .. tostring(m):gsub("[\r\n]", " "):sub(1, 100))
    return
end
if type(m) ~= "table" then
    print("VAL\t" .. name .. "\t" .. type(m) .. "\t" .. tostring(m))
    return
end
local keys = {}
for k, v in pairs(m) do
    if type(k) == "string" then keys[#keys + 1] = k .. ":" .. type(v) end
end
table.sort(keys)
print("API\t" .. name .. "\t" .. table.concat(keys, ",", 1, math.min(#keys, 40)))
```

**Driver**: for every name from §8.3, run the probe in **its own process** so that `pl` / `pl.strict` rewriting `_G` cannot contaminate later results; give each process a timeout (e.g. 20s). Collect `OK/ERR/API/VAL` lines with Python `subprocess` and aggregate them into TSV.

```python
import json, subprocess
names = json.load(open("module_names.json"))
for n in names:
    p = subprocess.run(["rfsh", "lua", "probe.lua", n],
                       capture_output=True, timeout=20)
    # Note: console output may be GBK-encoded; decode it with errors="replace"
    ...
```

**Probe B: functional spot checks**. A successful `pcall(require, name)` does **not** mean the module is callable (the two traps being metatable exports and lazy dependencies). For each module declared "usable", pick one representative function and `pcall` it again; label "loads but calls fail" separately as **Partially available**.

**Probe C: template smoke test**. Assemble the §5 templates into one script and run it to confirm the examples in this document contain no invented APIs.

### 8.5 Document Structure and Writing Conventions

- Fixed 9 sections: §0 hard constraints / §1 entry points / §2 runtime environment (including the complete 2.5 list and the 2.6 quick reference) / §3 namespace APIs / §4 conventions / §5 templates / §6 pitfalls / §7 location hints / §8 generation method.
- Every non-obvious conclusion must carry **(live-tested)** or be explicitly marked "inferred from source, not live-tested".
- The §2.5 table columns are fixed as `require | Returns | Purpose | Status`; status values are only `Available` / `Partially available` / `Unavailable + reason`.
- Pitfalls (§6) are ordered by **likelihood of being hit**; append new pitfalls at the end and renumber.
- Put the document date at the top; state the Lua version, architecture, and build mode together with it.

### 8.6 Pre-Publish Redaction Check (**Go Through Every Item Before Publishing Online**)

| Must not appear | Replace with |
|---|---|
| Absolute repo root paths, drive-letter paths, build artifact directories | Delete outright, or use an abstract description such as `rfsh` (debug build) |
| User home directory / username / hostname | Delete |
| Internal source directory hierarchies | Keep only **symbol names** or **single filenames**, never a directory tree |
| Local sample files (e.g. temp files with a drive letter) | `input.txt` / `app.ini` / `job.lua` / `some/dir/file.txt` |
| Real IP / MAC / product version number / full exe path | `<version string>`, `—`, or an abstract description |
| Full error paths of internal VFS mount points | Keep only the module name and line number, e.g. `pl/tablex.lua:106` |

**Automatic check**: after generation, search the whole document for drive-letter patterns, user directory keywords, internal source directory hierarchy terms, build artifact directory terms, temp directory terms, and real IPs / MACs / hostnames; any hit requires manual confirmation or deletion. API names, module names, algorithm names, error text, and package entry names **are not private — keep them**.

### 8.7 Update Procedure Checklist

1. Locate the data source categories per §8.1; confirm the `rfsh` executable was built from the current source (compare timestamps to avoid observing old behavior).
2. Re-extract the complete host API function set per §8.2 and diff it line by line against §3.
3. Re-extract the embedded package list per §8.3 and diff it line by line against §2.5 (added/removed modules, status changes).
4. Run the three probes per §8.4; write any newly appearing failure reasons into the §2.5 table and §6.
5. Update the loading mechanism description in §1.3 (if the mount point, the `add_env` subdirectory list, or the `bin2c` rule changed).
6. Update the module counts in the §0 hard constraints, the **(live-tested)** entries, and the §5 templates.
7. **Run the redaction scan** per §8.6, then update the document date.
8. Read the whole document back once, confirming there are no placeholders left and no contradictory paragraphs.

---

> Maintenance note: the §2.5 table is generated from "embedded package list + live-run TSV", not written by hand; when regenerating, re-run §8.3/§8.4 first and then replace the table, to avoid manual omissions.
